简体   繁体   中英

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM