3
$\begingroup$

If I use NumberForm,it is a very nice answer

SeedRandom[1]
result1 = NumberForm[#, {Infinity, 2}] & /@ RandomReal[20, 20]

{16.35,2.23,15.79,3.76,4.83,1.31,10.84,4.62,7.92,14.01,4.24,14.97,8.46,4.95,19.54,16.50,18.51,11.56,5.86,4.16}

Just one defect,it is not can do any calculation with it anymore.Such as we cannot expect result1+2 will run normally.So I use Export and Import to process it like

result=Import[Export["tem.txt", result1, "List"], "List"]

{16.35,2.23,15.79,3.76,4.83,1.31,10.84,4.62,7.92,14.01,4.24,14.97,8.46,4.95,19.54,16.50,18.51,11.56,5.86,4.16}

The result is exactly what I want.But is there any elegant method can do this?

$\endgroup$
  • 1
    $\begingroup$ The two methods are contradictory in that they do completely different things. So it remains unclear what you actually want. Apparently, you're expecting to have all numerical output rounded (as in the second example). That would lead to all sorts of trouble in reusing the results, so it appears to be a very bad idea. $\endgroup$ – Jens Apr 26 '17 at 3:44
  • 1
    $\begingroup$ Maybe you want this: NumberForm[result1=RandomReal[20,20],{Infinity,2}] $\endgroup$ – Jens Apr 26 '17 at 3:50
2
$\begingroup$

How about

$PrePrint = NumberForm[#, {Infinity, 2}] &;
$\endgroup$
  • $\begingroup$ Good lesson for usage of Infinity.But actually we have not get those numbers what I want,just show it?I mean,you have not get a result1 with two digits after the decimal point,just show it in that form. $\endgroup$ – yode Apr 26 '17 at 2:55
  • 1
    $\begingroup$ You mean you're trying to mimic the behavior of… Er… rounding calculation by hand? $\endgroup$ – xzczd Apr 26 '17 at 3:16
  • $\begingroup$ Yep,something like that.. $\endgroup$ – yode Apr 26 '17 at 3:29
  • $\begingroup$ And I have include your usage of Infinity to my post.Hope do not mind that. $\endgroup$ – yode Apr 26 '17 at 3:31
  • $\begingroup$ Well, then I should say I doubt if simply controling the digit of number will work. As far as I can tell, many posts tagged with [precision] and [accuracy] have suggested that, the… Er … rounding rule of Mathematica and manual calculation have subtle difference, though their behaviors are similar. BTW, do you know there's no one-to-one correspondence between decimals and floating number? (See e.g. docs.python.org/3/tutorial/floatingpoint.html ) $\endgroup$ – xzczd Apr 26 '17 at 3:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.