CVr CVr - 22 days ago 6
Python Question

Is there an error of precision in that program?

I'm trying to verify a sum and it seems in that program I don't find exactly 0, is there an error ?

from mpmath import *
mp.dps = 1500

a=mpf(0.1)
p=mpf(2.)

def f1(x):
return (a-(mpf(1)-mp.sqrt(1-x**2)))**p*x

def f2(x):
return x*(x-a)**p

def f3(x):
return x**p

i=mp.quad(f1,[0,mp.sqrt(mpf(1)-mpf(0.9)**mpf(2))])
j=mp.quad(f2,[0,a])
k=mp.quad(f3,[0,a])

print i,j,k
print mp.fabs(i)+mp.fabs(j)-mp.fabs(k)


Even with 1500 digits I don't find exactly 0.

Answer

When you creating mpf instances from a Python float, the value you enter in your code is first converted into a 53-bit value and then converted to a high-precision value. You are working with values that are not what you are expecting.

If you are working with high-precision code, you should either initialize from a string or from an integer. Try the following instead:

from mpmath import *
mp.dps = 1500

a=mpf("0.1")
p=mpf(2)

def f1(x):
  return (a-(mpf(1)-mp.sqrt(1-x**2)))**p*x

def f2(x):
  return x*(x-a)**p

def f3(x):
  return x**p

i=mp.quad(f1,[0,mp.sqrt(mpf(1)-mpf("0.9")**mpf(2))])
j=mp.quad(f2,[0,a])
k=mp.quad(f3,[0,a])

print i,j,k
print mp.fabs(i)+mp.fabs(j)-mp.fabs(k)
Comments