Use SetPrecision or "backtick precision syntax"

In Mathematica, precision of a real number can be set by the SetPrecision function or the "backtick precision syntax". But the two approach have subtle differences.

In[1]:= x1 = SetPrecision[0.123, 20]
x2 = 0.123`20

Out[1]= 0.12299999999999999822

Out[2]= 0.12300000000000000000

In[3]:= x1 === x2
x1 == x2

Out[3]= False

Out[4]= False

However, x1 is between the two machine numbers closest to x2, x2P and x2M

In[5]:= x2P=SetPrecision[x2(1+$MachineEpsilon),Infinity]
x2M=SetPrecision[x2(1-$MachineEpsilon),Infinity]
x1<=x2P
x1>=x2M
Out[5]= 4431542033332569/36028797018963968
Out[6]= 4431542033332567/36028797018963968
Out[7]= True
Out[8]= True

And the two machine numbers closest to x1 are the same

In[9]:= x1P=SetPrecision[x1(1+$MachineEpsilon),Infinity]
x1M=SetPrecision[x1(1-$MachineEpsilon),Infinity]
Out[9]= 4431542033332569/36028797018963968
Out[10]= 4431542033332567/36028797018963968
In[11]:= x1P==x2P
x1M==x2M
Out[11]= True
Out[12]= True

Also, the result is the same if it used 20. instead of 20 in

In[1]:= x1=SetPrecision[0.123,20.]
Out[1]= 0.12299999999999999822

Error for using SetPrecision[x, 20] and x`20

An upper bound for the difference between SetPrecision[x, 20] and x`20 is the difference between xP and xM. For the above instance,

In[14]:= x1P-x1M
Log[2,%]
Out[14]= 1/18014398509481984
Out[15]= -54
[/code] 

I.e. the error in representing x2 by x1 in worst case is 2^-54 for my computer.

The actual difference between x1 and x2 for the instance of x = 0.123 is smaller.

In[21]:= x2-x1
Log[2,%]
Out[21]= 1.78*10^-18
Out[22]= -58.97

How to get clean looking precision programatically?

One hacky way to set precision programatically using ToPrecision and StringJoin functions

In[2]:= mengSetPrecision[x_,p_]:=ToExpression[ StringJoin[ToString[x],"`",ToString[p]]]
In[3]:= mengSetPrecision[0.123,20]//InputForm
Out[3]//InputForm=
0.123`20.

blog comments powered by Disqus