Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
Round: inconsistent behaviour?

Subject: Round: inconsistent behaviour?

From: Andrea

Date: 14 Jul, 2012 23:10:40

Message: 1 of 3

Hi,

After some struggle to realise what was wrong with a function, I noticed the followed happening when using round:

round(66.5)

ans =

    67

0.7*0.95*100

ans =

         66.5

round(0.7*0.95*100)

ans =

    66

Can someone explain this and possibly gve a solution?
What is even weirder is this:

c=66.5

c =

         66.5

K>> round(c)

ans =

    67

c=0.7*0.95*100

c =

         66.5

K>> round(c)

ans =

    66

What's happening??

Thanks

Subject: Round: inconsistent behaviour?

From: Nasser M. Abbasi

Date: 14 Jul, 2012 23:16:01

Message: 2 of 3

On 7/14/2012 6:10 PM, Andrea wrote:
> Hi,
>
> After some struggle to realise what was wrong with a function,
>I noticed the followed happening when using round:
>
> round(66.5)
>
> ans =
>
> 67
>
> 0.7*0.95*100
>
> ans =
>
> 66.5
>

No. The answer is not 66.5, it is 66.49999999999
That is why rounding is 66 not 67

EDU>> format long
EDU>> r=0.7*0.95*100

r =

   66.499999999999986


> What's happening??
>

What you see on the screen is always what is inside the register.

--Nasser

Subject: Round: inconsistent behaviour?

From: James Tursa

Date: 15 Jul, 2012 00:03:32

Message: 3 of 3

"Andrea" wrote in message <jtsu9g$gn6$1@newscl01ah.mathworks.com>...
> Hi,
>
> After some struggle to realise what was wrong with a function, I noticed the followed happening when using round:
>
> round(66.5)
>
> ans =
>
> 67
>
> 0.7*0.95*100
>
> ans =
>
> 66.5
>
> round(0.7*0.95*100)
>
> ans =
>
> 66
>
> Can someone explain this and possibly gve a solution?

The intermediate calculations cannot be represented exactly in IEEE double precision. E.g.,

>> num2strexact(0.7)
ans =
0.6999999999999999555910790149937383830547332763671875
>> num2strexact(0.7*0.95)
ans =
0.66499999999999992450483432548935525119304656982421875
>> num2strexact(0.7*0.95*100)
ans =
6.64999999999999857891452847979962825775146484375e1
 
You can find num2strexact here:

http://www.mathworks.com/matlabcentral/fileexchange/22239-num2strexact-exact-version-of-num2str

James Tursa

Tags for this Thread

No tags are associated with this thread.

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us