【问题标题】:How to force python float operation on float32 rather than float64?如何在 float32 而不是 float64 上强制 python 浮动操作?
【发布时间】:2013-12-25 02:43:41
【问题描述】:

我想对float32 而非float64 类型进行一些数学运算(+、-、*、/)。我需要对numbernumpy.array 进行这些操作,以及一些numpy 数学函数,例如sqrt mean。我该怎么做?

【问题讨论】:

标签: python numpy floating-point operators precision


【解决方案1】:

numpy.float32 会有帮助吗?

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

如果您想对 float32 进行数学运算,请将操作数转换为 float32 可能会对您有所帮助。

【讨论】:

【解决方案2】:

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

注意精度:

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

给予

arr_f64 =  [1.0000123456789 2.0000123456789 3.0000123456789]
arr_f32 =  [1.0000124000000 2.0000124000000 3.0000124000000]

【讨论】:

    猜你喜欢
    • 2019-07-28
    • 2014-04-15
    • 2019-11-28
    • 1970-01-01
    • 2018-07-07
    • 2016-05-15
    • 1970-01-01
    • 2023-02-07
    • 2015-08-10
    相关资源
    最近更新 更多