0

I wrote a simple Python code to understand math.isclose(). Why the status2 below issue a False, I'm expecting a True here.

Base on the reading: If no errors occur, the result will be:

abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)

So, my code below on status2 should goes like this (what I thought):

    1.00-0.99 <= max (1x10e-2 x 1.00, 0.0)
     0.01 <= max (0.01, 0)
          <= 0.01   ---->True  (but program sesult gives a 'False', why?)`

Below is my code

#!/usr/bin/env python3
import math

rel_tole = 1e-02
print ('rel_tole={0}'.format(rel_tole))

a= 1.00
b= 1.01
status= math.isclose(a,b,rel_tol=rel_tole,abs_tol=0.0)
print ('a={0},b={1},rel_tole={2}, status={3}'.format(a,b,rel_tole,status))


a= 1.00
b= 0.99
status= math.isclose(a,b,rel_tol=rel_tole,abs_tol=0.0)

print ('a={0},b={1},rel_tole={2}, status2={3}'.format(a,b,rel_tole,status))

print ('############################################')
rel_tole = 1e-01
print ('rel_tole={0}'.format(rel_tole))

a= 1.00
b= 1.01
status= math.isclose(a,b,rel_tol=rel_tole,abs_tol=0.0)
print ('a={0},b={1},rel_tole={2}, status3={3}'.format(a,b,rel_tole,status))


a= 1.00
b= 0.99
status= math.isclose(a,b,rel_tol=rel_tole,abs_tol=0.0)
print ('a={0},b={1},rel_tole={2}, status4={3}'.format(a,b,rel_tole,status))

Result:

rel_tole=0.01
a=1.0,b=1.01,rel_tole=0.01, status=True
a=1.0,b=0.99,rel_tole=0.01, status2=False
############################################
rel_tole=0.1
a=1.0,b=1.01,rel_tole=0.1, status3=True
a=1.0,b=0.99,rel_tole=0.1, status4=True

Thank you.

glhr
  • 4,439
  • 1
  • 15
  • 26
Grace
  • 440
  • 3
  • 6
  • 21
  • 3
    If you use e.g. `format(n, ".40f")` you can see that `0.01` is actually smaller than `1 - 0.99`, so the comparison falls outside the tolerance; `0.01 < (1 - 0.99)`. See e.g. https://stackoverflow.com/q/588004/3001761. – jonrsharpe May 06 '19 at 07:18
  • Thank you for your answer but is there a way to get rid of this problem in such situation? I noticed that when I removed line 'status= math.isclose(a,b,rel_tol=rel_tole,abs_tol=0.0)' except the first one, now everything become 'True'. Which is weird to me. – Grace May 06 '19 at 07:36

0 Answers0