I want to show examples of round-off errors in some numerical algorithms to my student, in order to motivate the study of algorithms with a better behavior.
While it is easy in any other language, I found it horrendously complicated in Mathematica. Precision is tracked dynamically which makes SetPrecision[ ..., p]
not useful to exhibit roundoff problems.
I found out that ScientificForm
(maybe with Round[]
on top) could do the job, and I spent hours to try to get the output of ScientificForm
in expression but failed so far...
I desperately want:
a=SetPrecision[5.291/0.003, 4]
to be strictly equal to 1764
not 1763.67`4
so that I don't get different results when I input:
{SetPrecision[a*59.16, 4], SetPrecision[1764*59.16, 4]}
(* {1.043*10^5, 1.044*10^5} *)
(this can be obtained by Round[a]
but I want the same thing for small or large numbers where Round
does not work)
Any simple method to achieve that?
Edit: After several clever answers (but maybe not simple enough) whom authors I am grateful to, due to the level of the students I think I am going to show the example myself with a projector to students and let them program easier stuffs. Thanks again.
5.291`4/0.003`4
, which returns exactly1764.
$\endgroup$5.291
4/0.0034 // InputForm
returns exactly1763.6666666666666618178`3.6989700043360187
, which displays as1764.
. Note the many extra guard digits and loss of precision. I don't think arbitrary-precision numbers will work as fixed-precision numbers. $\endgroup$