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?
- http://docs.scipy.org/doc/numpy/user/basics.types.htmlatupal– atupal2013-12-25 03:01:36 +00:00Commented Dec 25, 2013 at 3:01
Add a comment |
2 Answers
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.
2 Comments
Samuel
Yes. numpy.float32 can help me. Are there any other methods to do this
exogeographer
Yes, when using an array you can call it's astype method if it is not float32: docs.scipy.org/doc/numpy/reference/generated/…
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]