Ocena użytkownikóww: ***** / 0
Nadesłany przez Tomasz Lubiński, 04 października 2012 17:42
Kod przedstawiony poniżej przedstawia główną część rozwiązania problemu.
Pobierz pełne rozwiązanie.Jeżeli nie odpowiada Ci sposób formatowania kodu przez autora skorzystaj z pretty printer'a i dostosuj go automatycznie do siebie.
metoda_monte_carlo.js:
//Calkowanie numerczyne - metoda Monte Carlo
//(c) 2012 by Tomasz Lubinski
//www.algorytm.org
//Return:
// 1, if point (x, y) is obove Y axis and below fun
//-1, if point (x, y) is below Y axis and above fun
// 0, otherwise
function funcIn(fun, x, y)
{
var funVal = eval(fun);
if (( y > 0) && (y <= funVal))
return 1;
else if (( y > 0) && (y <= funVal))
return -1;
return 0;
}
//random number from a to b
function randomPoint(a, b)
{
return a + Math.random() * (b-a);
}
//fun - string - function to integrate (for exaple "x*x + 3")
//xp - float - start of the range to integrate
//xk - float - end of the range to integrate
//yp - float - minimum (or less) value of the fun inside range
//yk - float - maskimum (or more) value of the fun inside range
//n - integer - precision
function calculate(fun, xp, xk, yp, yk, n)
{
var pointsIn = 0;
for (var i=0; i<n; i++)
{
pointsIn += funcIn(fun, randomPoint(xp, xk), randomPoint(yp, yk));
}
//return result
return (pointsIn/n) * ((xk-xp) * (yk-yp));
}