Calculate percent value

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Filip
Posts: 4
Joined: Sat Nov 20, 2021 9:50 pm

Re: Calculate percent value

Post by Filip » Wed Jan 19, 2022 2:24 pm

davef wrote:
Wed Jan 05, 2022 6:52 pm
Maybe I should have said "decimal" places. Especially with 1-wire measurements and using round 1 on the returned floating point number, I would often get:
66.4
66.30001
66.2
FYI: I learned this today:

Code: Select all

if 66.3 == round(66.30001, 1):
    print("Rounding is fine")
print("This should not print 66.30001 on Pico but it does:", 66.3)

User avatar
scruss
Posts: 360
Joined: Sat Aug 12, 2017 2:27 pm
Location: Toronto, Canada
Contact:

Re: Calculate percent value

Post by scruss » Wed Jan 19, 2022 4:26 pm

round() returns a float, and 66.3 is one of those numbers that doesn't have an exact representation in single-precision float.

If you think about it, in 32 bits, there are of the order of 2^32 (roughly 4.3 * 10^9) distinct values you can store. And yet, we somehow manage to jam the number range of roughly +/- 10^38 into those 32 bits. So there must be some (quite a lot, actually) of numbers we can't represent as a float.

So best to use format, f-strings or the '%' operator rather than round. And please, don't feed that rounded value back into your program unless you want to discover chaos theory all over again.

(NB: old notation alert, for i am old: "^" means "to the power of" here. I don't know how the cool kids type it today. I thought it might be more readable than "4.3E09", which is more my jam)

KJM
Posts: 158
Joined: Sun Nov 18, 2018 10:53 pm
Location: Sydney AU

Re: Calculate percent value

Post by KJM » Wed Jan 19, 2022 11:09 pm

I've been dodging the round problem by sticking to integers. With battery voltage for example that means working in mV then diving by 1000 at the end when it's time to print or otherwise output a result. The other advantage of sticking with integers is you can do an integer division (//) anytime intermediate results get cluttered with a stupid number of decimal places & not worry too much about accuracy loss.

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: Calculate percent value

Post by pythoncoder » Fri Jan 21, 2022 10:04 am

scruss wrote:
Wed Jan 19, 2022 4:26 pm
...
If you think about it, in 32 bits, there are of the order of 2^32 (roughly 4.3 * 10^9) distinct values you can store. And yet, we somehow manage to jam the number range of roughly +/- 10^38 into those 32 bits. So there must be some (quite a lot, actually) of numbers we can't represent as a float...
Given the infinity (aleph one) of reals between 0 and 1 that is very true :lol:
Peter Hinch
Index to my micropython libraries.

Post Reply