MATLAB: Weird results of Calculating Integration of Normal/Gaussian Distribution

integral integration normaldistribution gaussiandistribution

I wrote a simple function as same as the Normal/Gaussian Distribution with mean of 0 and sigma as the standard deviation.
The integration results with "integral" function seemed so whimsical in some cases with specific boundaries.
To my knowledge, the integration of Normal Distribution with boundaries of (-inf,inf) should be 1, while the integration with boundaries of (-n*sigma,n*sigma) should be close enough to 1, when n>=5 .
clear;close all;format long
sigma = 0.05; % the standard deviation
G1 = @(X) exp(-X.^2/(2*sigma^2) )/(sigma*sqrt(2*pi) ); % the normal/Gaussian distribution
clc
n = 18; % -n*sigma defines the lower bound
x1 = 1000; % x1 defines the upper bound 1
x2 = 5000; % x2 defines the upper bound 2
[integral(G1, -n*sigma, 0),1/2; % should be close to 1/2

integral(G1, 0, x1),1/2; % should be close to 1/2
integral(G1, -n*sigma, x1),1; % should be close to 1

integral(G1, x1, x2),0; % should be close to 0
integral(G1, -n*sigma, x2),1] % should be close to 1
However, the result I got was like below:
ans =
0.500000000000000 0.500000000000000
0.500000000000252 0.500000000000000
0.000000000013511 1.000000000000000
0 0
1.000000000001456 1.000000000000000
The 3rd row of the results, which was expected to be close to 1, was calculated to be 0.000000000013511
Besides, if the value of x1 was changed as x1 = 988, the result would be 0.999999999999933, which was quite close to the correct answer of 1; However, if x1 = 989 was chosen, the result would immediately turned to 0.000000000099978, which made me surprise.
My question is, why the "integral" function is so sensitive to the boundaries that even a slightly changing would lead to larger difference between the results? And, how could the "weird result" be avoided or excluded?
Thank you.

Best Answer

See the documentation section on: Accuracy of Floating-Point Data (link).
You are seeing the result of floating-point approximation error. There are many discussions of it in MATLAB Answers, so I’ll not go into detail here.