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.

3
  • It would help giving examples of what you are trying to do, does this help: stackoverflow.com/a/11523128/5236575? Commented Sep 10, 2021 at 6:36
  • Is there a reason you would need to round from 32 bits instead of 64 bits? Commented 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. Commented Sep 10, 2021 at 12:07

2 Answers 2

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))

Sign up to request clarification or add additional context in comments.

Comments

2

try using numpy float32

np.float32(6.33333333333)

you should read this other question.

1 Comment

Unfortunately, np.round() and np.around() don't function the same as Math.fround(). Thank you though!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.