1

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.

TrueGrace
  • 15
  • 6
  • It would help giving examples of what you are trying to do, does this help: https://stackoverflow.com/a/11523128/5236575? – shoaib30 Sep 10 '21 at 06:36
  • Is there a reason you would need to round from 32 bits instead of 64 bits? – Jason Chia Sep 10 '21 at 06: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 Sep 10 '21 at 12:07

2 Answers2

3

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))
blhsing
  • 91,368
  • 6
  • 71
  • 106
2

try using numpy float32

np.float32(6.33333333333)

you should read this other question.

JPcode
  • 90
  • 7