Getting weird results when calculating an integral using rectangle method

7 ビュー (過去 30 日間)
user4050
user4050 2020 年 4 月 2 日
コメント済み: user4050 2020 年 4 月 3 日
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?

採用された回答

John D'Errico
John D'Errico 2020 年 4 月 3 日
Look carefully at what you did.
vec1 = pi/180*(0.005:0.01:14.995);
Now, what is the stride between elements of that vector? While you may THINK about this as being in degrees, the vector is itself in radians. Those boxes have width dx. NOT 0.01. The value of dx here is 0.01*pi/180.
dx = diff(vec1(1:2))
dx =
0.000174532925199433
0.01*pi/180
ans =
0.000174532925199433
int_val = sum(dx*sin(vec1))
int_val =
0.03407417375418

その他の回答 (1 件)

Tommy
Tommy 2020 年 4 月 3 日
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 件のコメント
user4050
user4050 2020 年 4 月 3 日
Thanks. The two examples were elucidating as well.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangePerformance and Memory についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by