0

i have a strange problem. i have this piece of code and i don't understand why the first print instruction gives different result for the operation

abs(miaradq(n)-math.sqrt(n))

the code is this:

def miaradq(a):
    x = 5
    while True:
        y = (x + a/x) / 2
        if x == y:
            return x
            break
        x = y

def test_radq():
    for n in range (1,10):
      print('the difference between miasqrt and math.sqrt is %f', abs(miaradq(n) - math.sqrt(n)))

with this print function i get all 0.000000, but if i use

print(abs(miaradq(n) - math.sqrt(n)))

i get

0.0
2.220446049250313e-16
0.0
0.0
0.0
0.0
0.0
4.440892098500626e-16
0.0

i tried with %d too, but no luck. the only way to get this result with the formatted string is to use %s, i don't understand what i am missing here.

jane12
  • 1
  • 3
  • The numeric values have nothing to do with `print`. It is because of the actual calculation. Using different formatting in `print` is how to make very small numbers that are close to zero, appear as zero. The `%f` formatting is *explicitly asking* to show the result of the computation as accurately as possible. It just happens that this result isn't what you expected it to be. – Karl Knechtel Jan 09 '23 at 23:26

0 Answers0