Question

I want to do some math operations (+, -, *, /) on float32 rather than on float64 type. I need do these operations on number or numpy.array, and also some numpy math functions, such as sqrt mean. How do I do this?

Was it helpful?

Solution

Will numpy.float32 help?

>>>PI=3.1415926535897
>>> print PI*PI
9.86960440109
>>> PI32=numpy.float32(PI)
>>> print PI32*PI32
9.86961

If you want to do math operation on float32, convert the operands to float32 may help you.

OTHER TIPS

Use numpy.ndarray.astype:

import numpy as np

arr_f64 = np.array([1.0000123456789, 2.0000123456789, 3.0000123456789], dtype=np.float64)
arr_f32 = arr_f64.astype(np.float32)

Pay attention to precision:

np.set_printoptions(precision=16)
print("arr_f64 = ", arr_f64)
print("arr_f32 = ", arr_f32)

gives

arr_f64 =  [1.0000123456789 2.0000123456789 3.0000123456789]
arr_f32 =  [1.0000124000000 2.0000124000000 3.0000124000000]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top