Is there an easy way to make Python round using 32 bits instead of 64 bits? It would work in the same way as JavaScript's Math.fround, but I've ran circles in my head failing to come up with a solution.
-
It would help giving examples of what you are trying to do, does this help: stackoverflow.com/a/11523128/5236575?shoaib30– shoaib302021-09-10 06:36:58 +00:00Commented Sep 10, 2021 at 6:36
-
Is there a reason you would need to round from 32 bits instead of 64 bits?Jason Chia– Jason Chia2021-09-10 06:41:11 +00:00Commented Sep 10, 2021 at 6:41
-
I'm using a seeded pseudorandom generator from a video game and the values were off because it wasn't being rounded from 32 bits.TrueGrace– TrueGrace2021-09-10 12:07:46 +00:00Commented Sep 10, 2021 at 12:07
Add a comment
|
2 Answers
One quick way to do it is to assign the number to the value of a ctypes.c_float object:
from ctypes import c_float
d = 1.2345678901234567890
f = c_float()
f.value = d
print(d) # 64-bit double
print(f.value) # 32-bit float
This outputs:
1.2345678901234567
1.2345678806304932
Compared to Math.fround in JavaScript:
console.log(Math.fround(1.2345678901234567890))