Message Boards Message Boards

0
|
6156 Views
|
7 Replies
|
0 Total Likes
View groups...
Share
Share this post:

Strange behavior of Round[x_, .1] -- I want Round[2.40, .1] to be 2.4

Posted 9 years ago
InputForm[Round[2.40, .1]]

returns 2.4000000000000004

why isn't it 2.4 ??

how can I get it to return 2.4, or more generally, how can I get numbers approximated to n decimal places?
And I mean how do I really change the value; I know I can use NumberForm to change what is printed.

POSTED BY: Elaine Kant
7 Replies

Mathematica uses binary floating point representation for approximate numbers (i.e. numbers with a decimal point). That means that you can never exactly represent a rational number whose denominator is not a power of 2 with an approximate number.

POSTED BY: John Doty

Thanks, but NumberForm also only affects the print form.

I think this may actually do what I want! N[Rationalize[Round[2.40000004, .01]]]]

In[12]:= InputForm[N[Rationalize[Round[2.400004, .1]]]]

Out[12]//InputForm= 2.4

POSTED BY: Elaine Kant

In[3]:= NumberForm[2.40, {2, 1}]

Out[3]//NumberForm= \!( TagBox[ InterpretationBox["\<\"2.4\"\>", 2.4, AutoDelete->True], NumberForm[#, {2, 1}]& ])

POSTED BY: S M Blinder

In particular, this seems crazy to me:

In[9]:= SubsetQ[Map[Round[#, .1] &, {2.400001}], {2.4}]

Out[9]= False

In[10]:= Round[2.400002, .1] == 2.4

Out[10]= True

Yes, I know I can write my own form of SubsetQ, but I would think there were be some way to get a real 2.4 out of 2.400001 or whatever.

POSTED BY: Elaine Kant

Thanks, but that still affects the printing rather than the internal value:

In[1]:= InputForm[SetPrecision[2.40000032783267236526523651, 2]]

Out[1] = 2.40000032783267236526523651`2.

I guess it doesn't matter since both that and Round result in numbers that are said to be equal

In[2]:= Out[1] == 2.4

Out[2] = True

but it still bugs me.

POSTED BY: Elaine Kant

but it still bugs me.

Then see this Table command not obeying limits related discussion, please. The value 2.4 as a rational number is 24/10. Everything else is subject to a number representation.

POSTED BY: Udo Krause

Give SetPrecision a try

In[4]:= SetPrecision[2.40000032783267236526523651, 2]
Out[4]= 2.4

In[5]:= SetPrecision[2.40000032783267236526523651, 2] + 2.
Out[5]= 4.4
POSTED BY: Udo Krause
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract