Function "round" in python3 not working
-
Python 3.6.0 (default, Mar 27 2018, 01:18:40) [GCC 5.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import AdcExp >>> adc_1 = AdcExp.AdcExp(address=0x48) >>> accel_volt_x = adc_1.read_voltage(0) >>> g_x = (accel_volt_x - 1.51) / 0.35 >>> g_x 0.34267857142857155 >>> round(g_x, 1) 0.29999999999999999
I want to round the number to tenths, but 'round' does not work correctly.
-
@CAP-33 python rounding is a pain point for many users for quite some time, using your value for g_x try this:
print (round(g_x))
result is 0
Now try this: print (round (g_x,2))
result is 0.34000000000000002
and now this: print (round (g_x,2) * 2)
result is 0.68000000000000005
Why is the final 5 not a 4 which is 2 x 2?
Now try this:
print("% 0.2f" %(g_x))
the result is 0.34 which is what you would expect.
So we can better understand how rounding in python performs, set g_x to
g_x = 0.34567999999999So a round up to 2 decimal places would be 0.35 while a truncation would be 0.34.
round (g_x,2) produces a result of 0.34999999999999998 which if you rounded to 2 decimal places would be 0.35. You can see it is modifying the storage in order to produce a correctly rounded result.
Now try this:
print("% 0.2f" %(g_x)) outputs 0.35 which is what you would expect.Another reason why I consider python to be junk. junk. junk.
But this is not a question for the Onion forums, it's really a question for a Python forum because it's a quirk/junk in python
-
@crispyoz
Many thanks. I like python, but it, like other languages, has its drawbacks.
-
@CAP-33 You are correct this is a "drawback" of python. I find python has a lot of drawbacks That's why I develop my apps using C.