MATLAB Answers

How parentheses effects multiplication with pi ?

7 views (last 30 days)
Emre Doruk
Emre Doruk on 4 Aug 2020
Edited: Bruno Luong on 5 Aug 2020
I am trying to generate sine wave. I am usning following two code lines. But they are slightly different (about e-15). Why is it happenning ? What is the differences of two lines;
sing1= sin (2*pi*f0*t);
sing2= sin(2*pi*(f0*t));
Thanks for your help,


Sign in to comment.

Accepted Answer

Bruno Luong
Bruno Luong on 5 Aug 2020
Edited: Bruno Luong on 5 Aug 2020
"While floating-point addition and multiplication are both commutative (a + b = b + a and a × b = b × a), they are not necessarily associative. That is, (a + b) + c is not necessarily equal to a + (b + c). ... "
  • "(2*pi*f0*t)" interpreted by MATLAB as ((2*pi)*f0)*t
  • "2*pi*(f0*t)" interpreted by MATLAB as (2*pi)*(f0*t)
As floating-point multiplication is NOT ASSOCIATIVE, both results might be different.


Show 2 older comments
Emre Doruk
Emre Doruk on 5 Aug 2020
Thanks for your answer, again. I can see your point.
Bruno Luong
Bruno Luong on 5 Aug 2020
Sometime this non-associativity is a real headeach, such as finding a limits of a sign- alternate series by partial sum, or integral of an oscillated signal (any wave propagation SW might encounters this). There is a real challenge to know what really the limits and the order of the sum can make the result change widely.
Emre Doruk
Emre Doruk on 5 Aug 2020
Actually I realized it recently, I thougth this problem is about pi. Because it is irrational and maybe MATLAB coverge it sth. I asked for this reason but I see that it is more common from this. I should check all of my old codes which needs exact values. Genereally it can be accept like precision mistake but sometimes I really need exact value.

Sign in to comment.

More Answers (1)

madhan ravi
madhan ravi on 4 Aug 2020
In the first the order of operation is from left to right.
In the second the order of operation is inside the parenthesis and then the outer.


Show 4 older comments
Stephen Cobeldick
Stephen Cobeldick on 5 Aug 2020
"Because it is the same oparetaion, left to right or the right to left. "
No, that is incorrect.
In general operations on binary floating point numbers are NOT associative:
A classic example of this is called catastrophic cancelation:
>> (1 + 1e100) - 1e100
ans =
>> 1 + (1e100 - 1e100)
ans =
"Why is it happenning?"
Because of the well-documented properties of binary floating point numbers.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by