What is causing this strange Mathematica result?

元气小坏坏 提交于 2019-12-04 10:07:36

Welcome to the world of machine precision. If you examine 1.05 +.10 and 1.15 more closely, you'll see that they're not quite the same:

1.05 + .10 // FullForm

==> 1.1500000000000001`

1.15 // FullForm

==> 1.15`

In addition to incurring small errors when using MachinePrecision, the same floating-point calculation can produce slightly different results at different times of the day. This is not a bug, but rather a by-product of how modern hardware floating-point architectures work

This means you should not use operations like ReplaceAll that depend on knowing exact value of MachinePrecision numbers. Using == (and ===) might be OK because they ignore last 7 (respectively 1) binary digit of MachinePrecision numbers.

Using Mathematica arithmetic should give exact results regardless of time of day, you could use it for your example as follows (10 significant digits)

0.05`10 + .10`10 /. {0.15`10 -> "pass"}
1.04`10 + .10`10 /. {1.14`10 -> "pass"}
1.05`10 + .10`10 /. {1.15`10 -> "pass"}
1.15`10 /. {1.15`10 -> "pass"}

Update: What Every Computer Scientist Should Know About Floating-Point Arithmetic gives some more caveats about floating point arithmetic. For instance, page 80 gives examples of how different implementations of IEEE 754 give slightly different results, even despite being standard compliant

Your replacements only work on exact matches, whereas your While statement uses Equal. You can make the rule based approach work by using Equal as well.

0.05 + .10 /. {x_ /; x == 0.15 -> "pass"}
1.04 + .10 /. {x_ /; x == 1.14 -> "pass"}
1.05 + .10 /. {x_ /; x == 1.15 -> "pass"}
1.15 /. {x_ /; x == 1.15 -> "pass"}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!