Files
MonteCarlo-Matlab/MonteCarloMatlab.m
2024-05-16 12:27:29 +02:00

54 lines
1.1 KiB
Matlab

tic;
samples = 100000;
xBounds = LinearBounds(0,20);
yBounds = LinearBounds(-10,150000);
bounds = Bounds(xBounds,yBounds);
pointsInside = 0;
realValue = realIntegral(bounds.x);
listOfErrors = [];
listOfIntegrals = [];
for i = 1:20
for ii = 0:samples
toTestPoint = bounds.getRandomPoint;
if getIsInside(toTestPoint)
pointsInside = pointsInside+1;
end
end
listOfIntegrals(i) = pointsInside/samples*bounds.area;
listOfErrors(i) = abs(listOfIntegrals(i) - realValue);
pointsInside = 0;
end
format longG
integral = (pointsInside/samples)*bounds.area
realValue
error = abs(realValue-integral)
listOfErrors
listOfIntegrals
toc
function out = mainFunction(x)
out = x^4-4*x^3+18*x^2-12*x-69;
end
function out = indefiniteIntegral(x)
out = (1/5)* x^5 - x^4 + 6* x^3 - 6*x^2 - 69*x;
end
function out = getIsInside(p)
arguments
p Point
end
y_0 = mainFunction(p.x);
out = abs(y_0) > abs(p.y) && y_0 * p.y >= 0;
end
function out = realIntegral(bounds)
arguments
bounds LinearBounds
end
out = indefiniteIntegral(bounds.higher) - indefiniteIntegral(bounds.lower);
end