gpt4 book ai didi

python - SciPy 和 NumPy 之间的关系

转载 作者:IT老高 更新时间:2023-10-28 12:10:29 24 4
gpt4 key购买 nike

SciPy 似乎在其自己的命名空间中提供了 NumPy 的大部分(但不是全部 [1])函数。换句话说,如果有一个名为 numpy.foo 的函数,那么几乎肯定有一个 scipy.foo。大多数时候,两者看起来完全一样,甚至经常指向同一个函数对象。

有时,它们是不同的。举一个最近出现的例子:

  • numpy.log10ufunc为否定参数返回 NaN;
  • scipy.log10 为负参数返回复数值,并且看起来不是 ufunc。

loglog2logn 也可以这样说,但 log1p 则不然 [2] .

另一方面,numpy.expscipy.exp 似乎是同一个 ufunc 的不同名称。 scipy.log1pnumpy.log1p 也是如此。

另一个例子是 numpy.linalg.solve vs scipy.linalg.solve。它们相似,但后者比前者提供了一些额外的功能。

为什么会出现明显的重复?如果这意味着将 numpy 批量导入到 scipy 命名空间中,为什么会有细微的行为差异和缺少的功能?是否有一些总体逻辑可以帮助消除混淆?

[1] numpy.minnumpy.maxnumpy.abs 和其他一些在 中没有对应项scipy 命名空间。

[2] 使用 NumPy 1.5.1 和 SciPy 0.9.0rc2 测试。

最佳答案

上次查了一下,scipy的__init__方法执行了一个

from numpy import *

以便在导入 scipy 模块时将整个 numpy 命名空间包含到 scipy 中。

您描述的 log10 行为很有趣,因为 两个 版本都来自 numpy。一个是 ufunc,另一个是 numpy.lib 函数。为什么 scipy 比 ufunc 更喜欢库函数,我不知道。


编辑:事实上,我可以回答 log10 的问题。查看 scipy __init__ 方法,我看到了这个:

# Import numpy symbols to scipy name space
import numpy as _num
from numpy import oldnumeric
from numpy import *
from numpy.random import rand, randn
from numpy.fft import fft, ifft
from numpy.lib.scimath import *

你在scipy中得到的log10函数来自numpy.lib.scimath。查看该代码,它说:

"""
Wrapper functions to more user-friendly calling of certain math functions
whose output data-type is different than the input data-type in certain
domains of the input.

For example, for functions like log() with branch cuts, the versions in this
module provide the mathematically valid answers in the complex plane:

>>> import math
>>> from numpy.lib import scimath
>>> scimath.log(-math.exp(1)) == (1+1j*math.pi)
True

Similarly, sqrt(), other base logarithms, power() and trig functions are
correctly handled. See their respective docstrings for specific examples.
"""

似乎模块覆盖了 sqrtloglog2lognlog10powerarccosarcsinarctanh。这解释了您所看到的行为。这样做的根本设计原因可能隐藏在某处的邮件列表帖子中。

关于python - SciPy 和 NumPy 之间的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6200910/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com