2

I'm going to take an integer number, then print root of that with sqrt function in float number to 4 decimal places without any rounding; but I have a problem. For example, when I take 3 as input, the output is 1.7320. It is correct; but when I take 4 as input, I expect 2.0000 as output; but what I see is 1.9999. What am I doing wrong?

import math
num = math.sqrt(float(input())) - 0.00005
print('%.4f' % num)
Ehsan R
  • 61
  • 1
  • 5
  • 2
    why is that surprising? sqrt of 4 is 2, and `2 - 0.00005` is `1.99995`... – Tomerikoo Jul 31 '19 at 15:52
  • 1
    Does [this answer to Python 3.x rounding behavior](https://stackoverflow.com/a/10826537/1115360) help? – Andrew Morton Jul 31 '19 at 15:57
  • 1
    if you run `print('%.16f' % num)` for example, you see that `num` is just a tiny bit smaller than 1.99995. `%.4f` consequently floors down to 1.9999. I think [this](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) is the right place to start reading further. – FObersteiner Jul 31 '19 at 15:58

2 Answers2

2

Check out Round float to x decimals?

One of the solutions from that page would be to replace your print statement with: print(format(num, '.4'))

Using modern f-strings: print(f'{num:.4f}')

vtnate
  • 133
  • 1
  • 9
1

Based on your expected output for the square root of 3, it seems that you really just want to truncate or extend the square root output to 4 decimal places (rather than round up or down). If that is the case, you could just format to 5 decimal places and slice off the last character in the string (examples below replace your input with hardcoded strings for illustration).

import math

n = '{:.5f}'.format(math.sqrt(float('3')))[:-1]
print(n)
# 1.7320

n = '{:.5f}'.format(math.sqrt(float('4')))[:-1]
print(n)
# 2.0000
benvc
  • 14,448
  • 4
  • 33
  • 54