[英]How to force python float operation on float32 rather than float64?
I want to do some math operations (+, -, *, /) on float32
rather than on float64
type.我想对
float32
而不是float64
类型进行一些数学运算(+、-、*、/)。 I need do these operations on number
or numpy.array
, and also some numpy math functions, such as sqrt mean
.我需要对
number
或numpy.array
以及一些 numpy 数学函数执行这些操作,例如sqrt mean
。 How do I do this?我该怎么做呢?
Will numpy.float32 help? numpy.float32 会有帮助吗?
>>>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.如果您想对 float32 进行数学运算,将操作数转换为 float32 可能会对您有所帮助。
Use numpy.ndarray.astype :使用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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.