Message Boards Message Boards

0
|
2982 Views
|
2 Replies
|
1 Total Likes
View groups...
Share
Share this post:

newbie question

Posted 11 years ago
when evaluating the following with "b=a+0.04" (or 0.03) the first 'Cases' fails however it seems to work fine for any other value (i.e. 0.02,0.06)
Q = {{0.1, 0.3, 1}, {0.2, 0.33, 2}, {0.3, 0.34, 3}, {0.4, 0.36,
   4}, {0.5, 0.38, 5}}
a = 0.3
b = a + 0.04
Cases[Q, {x_, b, z_}]
Cases[Q, {x_, 0.34, z_}]
POSTED BY: lei baida
2 Replies
Posted 11 years ago
thanks a lot, it works.
POSTED BY: lei baida
Posted 11 years ago
Welcome to floating point hell ;)

Mathematica stores numbers like 13.1441 in machine precision, this is an inexact way to represent numbers so strange things happen:
0.3 + 0.04 // FullForm
0.34 // FullForm
0.34 + 0.1 - 0.1 //FullForm

0.33999999999999997`
0.34`
0.3400000000000001`

Cases looks for things that matches exactly, and b doesn't exactly match 0.34, that is why it fails.
The == operator allows for a bit of machine error, so this wil work as expected:
Cases[Q, {x_, y_ /; y == b, z_}]

(* However this will not: *)
Cases[{2.00006 - 2.00005}, n_ /; n == 0.00001]

You can check the Basics of Numeric Computation for an overveiw of inexact and exact numbers
POSTED BY: Simon Schmidt
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