Getting the math right
Because I work regularly with developers on the MATLAB Math team, I see the questions that come to them from tech support. Today there was an interesting one.
A user observed that computing the sin function takes longer for very big numbers. The user asked, "Why is that?"
Well, first let's see if we can reproduce the observation. Start by making a vector with one million numbers in the interval [0,1].
rng(42) x = rand(1000000,1);
(I seeded the random number generator using rng so that the numbers below don't change each time I run this script.)
How long does it take to compute the sin of all those numbers?
f = @() sin(x); timeit(f)
ans = 0.002102730998500
Now repeat the timing experiment with another vector containing one million numbers in the interval [100000000,100000000+1].
x2 = x + 100000000; g = @() sin(x2); timeit(g)
ans = 0.027343141998500
The user is right, it does take longer!
Here's the straightforward explanation: For large numbers, it takes more computation to produce an accurate result.
To illustrate, let's look at the output of sin for one large number in MATLAB and compare it the result from another application. I'm going to use Excel for this comparison, but the results will be similar for code you write in C that calls the standard C math library function, sin().
z = x2(1)
z = 1.000000003745401e+08
matlab_result = sin(z)
matlab_result = 0.734111589042897
excel_result = 0.734111669990523
excel_result = 0.734111669990523
These two results agree to only 6 digits!
Let's use the Symbolic Math Toolbox to compute sin(z) with 20 decimal digits of accuracy.
sym_result = sin(sym(z))
sym_result = sin(3355443212567481/33554432)
vpa(sym_result,20)
ans = 0.73411158904289725019
From this calculation, you can see that the MATLAB result is accurate to 15 decimal digits, whereas the Excel result is accurate to only 6 digits.
That's called sweating the details.
评论
要发表评论,请点击 此处 登录到您的 MathWorks 帐户或创建一个新帐户。