我可以将 float128 设置为 numpy 中的标准浮点数组吗 [英] Can i set float128 as the standard float-array in numpy

查看:27
本文介绍了我可以将 float128 设置为 numpy 中的标准浮点数组吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我的数值程序有问题,我很好奇它是否是一个精度问题(即舍入误差).有没有一种快速的方法可以将我程序中的所有浮点数组更改为 float128 数组,而无需遍历我的代码并在所有地方键入 dtype='float128'.我的数组都是 float64,但我从未明确写过 dtype='float64',所以我希望有一种方法可以改变这种默认行为.

So I have a problem with my numerical program, and I'm curious about whether it is a precision problem (i.e. round-off error). Is there a quick way to change all the float arrays in my program into float128 arrays, without going through my code and typing dtype='float128' all over the place. My arrays are all float64, but i never explicitly wrote dtype='float64', so i was hoping there was a way to change this default behavior.

推荐答案

我不认为有一个中央配置"可以改变来实现这一点.您可以做的一些选择:

I don't think there is a central "configuration" you could change to achieve this. Some options what you could do:

  1. 如果您仅使用 NumPy 的少数工厂函数创建数组,请将这些函数替换为您自己的版本.如果你导入这些函数,比如

  1. If you are creating arrays only by very few of NumPy's factory functions, substitute these functions by your own versions. If you import these functions like

from numpy import empty

你可以做的

from numpy import float128, empty as _empty
def empty(*args, **kwargs):
    kwargs.update(dtype=float128)
    _empty(*args, **kwargs)

如果你正在做

import numpy

你可以写一个模块mynumpy.py

from numpy import *
_empty = empty
def empty(*args, **kwargs):
    kwargs.update(dtype=float128)
    _empty(*args, **kwargs)

并像导入一样

import mynumpy as numpy

  • 重构您的代码以始终使用 dtype=myfloat.这将使将来的此类更改变得容易.您可以将此方法与 numpy.empty_like()numpy.zeros_like()numpy.ones_like() 的使用结合起来在尽可能少的地方硬编码实际数据类型.

  • Refactor your code to always use dtype=myfloat. This will make such changes easy in the future. You can combine this approach with the use of numpy.empty_like(), numpy.zeros_like() and numpy.ones_like() wherever appropriate to have the actual data type hardcoded in as few places as possible.

    子类 numpy.ndarray 并且仅使用您的自定义构造函数来创建新数组.

    Sub-class numpy.ndarray and only use your custom constructors to create new arrays.

    这篇关于我可以将 float128 设置为 numpy 中的标准浮点数组吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆