Getting weird results when calculating an integral using rectangle method
Afficher commentaires plus anciens
Hi Guys,
I wrote the following code to try to integrate sin(x) from 0 to 15 (in degrees) using the rectangle method. I know there are other ways of calculating integrals in MATLAB, but this was out of curiosity, and I can't figure out what is going wrong. The code is as follows:
vec1 = pi/180*(0.005:0.01:14.995);
int_val = sum(0.01.*sin(vec1));
The idea is to use rectangles of width 0.01, and to calculate their areas using the midpoints between values. However, the result I get for "int_val" is 1.9523, which is obviously wrong (should be 0.0341). On the other hand, I have tried almost the exact same code to perform numerical integration on a different function (x^2, in this case) from x= 0 to 15, and obtained the correct result of 1125. This code is as follows:
vec1 = (0.005:0.01:14.995);
fun1 = @(x) x.^2;
int_val = sum(0.01*fun1(vec1));
It doesn't seem like some kind of silly math error, so can someone explain what is going wrong here?
Réponse acceptée
Plus de réponses (1)
Tommy
le 3 Avr 2020
vec1 = pi/180*(0.005:0.01:14.995);
Here, vec1 is in radians, but the values are not spaced 0.01 radians apart:
>> vec1(2)-vec1(1)
ans =
1.7453e-04
Rather, they are spaced 0.01*(pi/180) radians apart, so the width of each rectangle is 0.01*(pi/180):
int_val = sum(0.01*(pi/180)*sin(vec1));
int_val =
0.0341
Alternatively,
vec1 = ((pi/180)*0.005:0.01:(pi/180)*14.995);
int_val = sum(0.01*sin(vec1))
int_val =
0.0349
The rectangles are wider, so the estimate is less accurate.
1 commentaire
user4050
le 3 Avr 2020
Catégories
En savoir plus sur Performance and Memory dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!