Skip to content

Instantly share code, notes, and snippets.

@Bobingstern
Last active June 11, 2022 16:20
Show Gist options
  • Save Bobingstern/5889253a3bbf382bea6e5499925b37c0 to your computer and use it in GitHub Desktop.
Save Bobingstern/5889253a3bbf382bea6e5499925b37c0 to your computer and use it in GitHub Desktop.
JavaScript Numerical Integration
//Simpsons use rule fourth derivative for error calculation and minimisation
let GR = (Math.sqrt(5)+1)/2
function maximum(f,a,b,error){
error = error == undefined ? 1e-4 : error
let c = b - (b-a) / GR
let d = a + (b-a) / GR
while (Math.abs(b-a) > error){
if (f(c) > f(d)){
b = d
}
else{
a=c
}
c = b - (b-a) / GR
d = a + (b-a) / GR
}
return (a+b)/2
}
function NIntegrate(f,a,b){
//error = error == undefined ? 1e-4 : error
let error = 1e-5
//TODO: Make this more efficient and accurate
//If someone can write a function to take the 4th derivative of a function at point x pls tell me
function FourthDeriv(x){
let h = 1e-3
return Math.abs((f(x-2*h) - 4*f(x-h) + 6*f(x) - 4*f(x+h) + f(x+2*h))/h**4)
}
let M = maximum(FourthDeriv,a,b)
let N = Math.ceil(Math.pow((M*(b-a)**5)/(180*error),1/4))+1
let q = (b-a)/N
let sum = 0
for (let n=0;n<=N-1;n++){
sum += f(a+n*q)+2*f(a+(n+0.5)*q)
}
return q/3*(0.5*(f(b)-f(a))+sum)
}
//Example
function integrand(x){
return Math.sin(10*x)*Math.exp(-(x**2))
}
console.log(NIntegrate(integrand,0,2)) //0.10134
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment