Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 8082

MicroPython • int() doing odd things.

$
0
0
So, can anyone explain this? If run on a Pi Pico W 2 running MicroPython 1.25:

Code:

import mathprint("Should be 12.0 > "+str(math.log2(4096)))print("Should be 13.0 > "+str(math.log2(8192)))print("Should be 12 > "+str(round(math.log2(4096))))print("Should be 13 > "+str(round(math.log2(8192))))print("Should be 12 > "+str(int(math.log2(4096))))print("Should be 13 > "+str(int(math.log2(8192)))+" Wait?! Whaaaaaat?")
gives me this:

Should be 12.0 > 12.0
Should be 13.0 > 13.0
Should be 12 > 12
Should be 13 > 13
Should be 12 > 12
Should be 13 > 12 Wait?! Whaaaaaat?

Why is int() doing such a bad job of converting these specific numbers? On the sequence (1, 2, 4, 8 etc.) there are specific numbers it fails on:

Code:

import mathn=1for i in range(0,100):                    s1=str(round(math.log2(n)))    s2=str(int(math.log2(n)))    if s1!=s2: print("N: "+str(n)+" Round: "+s1+" Int: "+s2)        n=n*2
Gives me this:
N: 8192 Round: 13 Int: 12
N: 32768 Round: 15 Int: 14
N: 67108864 Round: 26 Int: 25
N: 1073741824 Round: 30 Int: 29
N: 562949953421312 Round: 49 Int: 48
N: 4503599627370496 Round: 52 Int: 51
N: 144115188075855872 Round: 57 Int: 56
N: 1152921504606846976 Round: 60 Int: 59
N: 9903520314283042199192993792 Round: 93 Int: 92
N: 316912650057057350374175801344 Round: 98 Int: 97

I am guessing it is a rounding issue deep inside MicroPython (full-fat Python doesn't exhibit this behaviour) but as these numbers should all result in whole numbers throughout, I am not sure why this is manifesting like this?

Statistics: Posted by HeMan321 — Sat Apr 26, 2025 11:25 pm



Viewing all articles
Browse latest Browse all 8082

Trending Articles