Steve on Image Processing with MATLAB

Image processing concepts, algorithms, and MATLAB


Steve on Image Processing with MATLAB has been archived and will not be updated.

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].

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);
ans =


Now repeat the timing experiment with another vector containing one million numbers in the interval [100000000,100000000+1].

x2 = x + 100000000;
g = @() sin(x2);
ans =


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 =


matlab_result = sin(z)
matlab_result =


excel_result = 0.734111669990523
excel_result =


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 =
ans =

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.

Published with MATLAB® R2016b

  • print


To leave a comment, please click here to sign in to your MathWorks Account or create a new one.