Javascript is used to implement the function integration algorithm.
The calculation result shows that the algorithm accuracy is greatly affected by the random number generator.
[Javascript]
// Monte carro calculates the definite integral of a given function
// Specify a function
Function f1 (x, xmin, xmax)
{
If (x> = xmin & x <= xmax)
Return x * Math. sqrt (1 + x * x)-1;
}
Function f2 (x, xmin, xmax)
{
If (x> = xmin & x <= xmax)
Return x * Math. log (1 + x );
}
Function f3 (x, xmin, xmax)
{
If (x> = xmin & x <= xmax)
Return Math. sqrt (1-x * x );
}
Function f4 (x, xmin, xmax)
{
If (x> = xmin & x <= xmax)
Return Math. cos (x)-0.9;
}
// Obtain the upper and lower limits of the function-the accuracy is greatly affected-if y> 0 is used for credits, the base limit is 0. If y is <0, the upper limit is 0; if y crosses the X axis, the default limit is not modified.
Function getLimit (func, xmin, xmax)
{
// Boundary Limit
Var t1 = func (xmin, xmin, xmax), t2 = func (xmax, xmin, xmax );
Var limit = {y0: Math. min (t1, t2), y1: Math. max (t1, t2 )};
Var delta = 1e-3, lastX, lastY;
For (var x = xmin, I = 0; x <= xmax; x + = delta, I ++)
{
Y = func (x, xmin, xmax );
If (y <limit. y0)
Limit. y0 = y;
If (y> limit. y1)
Limit. y1 = y;
If (I = 0)
{
LastX = x;
LastY = y;
}
Else
{
Var tx = (lastX + x)/2;
Var ty = func (tx, xmin, xmax );
If (Math. abs (lastY)> Math. abs (y ))
{
If (Math. abs (lastY) <Math. abs (ty ))
{
LastX = tx;
LastY = ty;
If (ty <0 & limit. y0> ty)
Limit. y0 = ty;
Else if (ty> = 0 & limit. y1 <= ty)
Limit. y1 = ty;
}
}
If (Math. abs (lastY) <Math. abs (y ))
{
If (Math. abs (y) <Math. abs (ty ))
{
LastX = tx;
LastY = ty;
If (ty <0 & limit. y0> ty)
Limit. y0 = ty;
Else if (ty> = 0 & limit. y1 <= ty)
Limit. y1 = ty;
}
}
}
}
If (limit. y0> 0)
Limit. y0 = 0;
If (limit. y1 <0)
Limit. y1 = 0;
Return limit;
}
// Points
Function cumulate (func, N, xmin, xmax)
{
Var limit = getLimit (func, xmin, xmax );
// Console. log ('limit = ', Limit. y0, limit. y1 );
Var x, yr, y;
Var cntA = 0, cntB = 0;
For (var I = 0; I <N; I ++)
{
X = xmin + (xmax-xmin) * Math. random ();
Yr = limit. y0 + (limit. y1-limit. y0) * Math. random ();
Y = func (x, xmin, xmax );
If (y> = 0 & yr> = 0 & yr <= y)
CntA ++;
Else
If (y <= 0 & yr <= 0 & yr> = y)
CntB ++;
}
// Console. log ('counts = ', cntA, cntB );
Return (cntA-cntB) * (xmax-xmin) * (limit. y1-limit. y0)/N;
}
// Test
Var t1, t2;
Var rst;
Var N = 1e7;
Var fs = [f1, f2, f3, f4];
Var ans = [-0.593682861167513, 0.25, Math. PI/4,-0.058529015192103493347497678369701];
For (var I = 0; I <4; I ++)
{
T1 = new Date ();
Rst = cumulate (fs [I], N, 0, 1 );
T2 = new Date ();
Console. log ('[', I, '] =', ans [I]. toFixed (15), rst. toFixed (15), t2-t1, 'ms ');
}