GVKun编程网logo

Python 的整数与 Numpy 的数据溢出(python整数溢出问题)

3

本文将带您了解关于Python的整数与Numpy的数据溢出的新内容,同时我们还将为您解释python整数溢出问题的相关知识,另外,我们还将为您提供关于"importnumpyasnp"ImportEr

本文将带您了解关于Python 的整数与 Numpy 的数据溢出的新内容,同时我们还将为您解释python整数溢出问题的相关知识,另外,我们还将为您提供关于"import numpy as np" ImportError: No module named numpy、3.7Python 数据处理篇之 Numpy 系列 (七)---Numpy 的统计函数、Anaconda Numpy 错误“Importing the Numpy C Extension Failed”是否有另一种解决方案、Difference between import numpy and import numpy as np的实用信息。

本文目录一览:

Python 的整数与 Numpy 的数据溢出(python整数溢出问题)

Python 的整数与 Numpy 的数据溢出(python整数溢出问题)

某位 A 同学发了我一张截图,问为何结果中出现了负数?

看了图,我第一感觉就是数据溢出了。数据超出能表示的最大值,就会出现奇奇怪怪的结果。

然后,他继续发了张图,内容是 print(100000*208378),就是直接打印上图的 E[0]*G[0],结果是 20837800000,这是个正确的结果。

所以新的问题是:如果说上图的数据溢出了,为何直接相乘的数却没有溢出?

由于我一直忽视数据的表示规则(整型的上限是多少?),而且对 Numpy 了解不多,还错看了图中结果,误以为每一个数据都是错误的,所以就解答不出来。

最后,经过学习群里的一番讨论,我才终于明白是怎么回事,所以本文把相关知识点做个梳理。

在正式开始之前,先总结一下上图会引出的话题:

  • Python 3 中整数的上限是多少?Python 2 呢?
  • Numpy 中整数的上限是多少?出现整数溢出该怎么办?

关于第一个问题,先看看 Python 2,它有两种整数:

  • 一种是短整数,也即常说的整数,用 int 表示,有个内置函数 int()。其大小有限,可通过sys.maxint() 查看(取决于平台是 32 位还是 64 位)
  • 一种是长整数,即大小无限的整数,用 long 表示,有个内置函数 long()。写法上是在数字后面加大写字母 L 或小写的 l,如 1000L

当一个整数超出短整数范围时,它会自动采用长整数表示。举例,打印 2**100 ,结果会在末尾加字母 L 表示它是长整数。

但是到了 Python 3,情况就不同了:它仅有一种内置的整数,表示为 int,形式上是 Python 2 的短整数,但实际上它能表示的范围无限,行为上更像是长整数。无论多大的数,结尾都不需要字母 L 来作区分。

也就是说,Python 3 整合了两种整数表示法,用户不再需要自行区分,全交给底层按需处理。

理论上,Python 3 中的整数没有上限(只要不超出内存空间)。这就解释了前文中直接打印两数相乘,为什么结果会正确了。

PEP-237(Unifying Long Integers and Integers)中对这个转变作了说明。它解释这样做的 目的:

这会给新的 Python 程序员(无论他们是否是编程新手)减少一项上手前要学的功课。

Python 在语言运用层屏蔽了很多琐碎的活,比如内存分配,所以,我们在使用字符串、列表或字典等对象时,根本不用操心。整数类型的转变,也是出于这样的便利目的。(坏处是牺牲了一些效率,在此就不谈了)

回到前面的第二个话题:Numpy 中整数的上限是多少?

由于它是 C 语言实现,在整数表示上,用的是 C 语言的规则,也就是会区分整数和长整数。

有一种方式可查看:

import numpy as np

a = np.arange(2)
type(a[0])

# 结果:numpy.int32

也就是说它默认的整数 int 是 32 位,表示范围在 -2147483648 ~ 2147483647。

对照前文的截图,里面只有两组数字相乘时没有溢出:100007*4549、100012*13264,其它数据组都溢出了,所以出现奇怪的负数结果。

Numpy 支持的数据类型要比 Python 的多,相互间的区分界限很多样:

截图来源:https://www.runoob.com/numpy/numpy-dtype.html

要解决整数溢出问题,可以通过指定 dtype 的方式:

import numpy as np

q = [100000]
w = [500000]

# 一个溢出的例子:
a = np.array(q)
b = np.array(w)
print(a*b)  # 产生溢出,结果是个奇怪的数值

# 一个解决的例子:
c = np.array(q, dtype=''int64'')
d = np.array(w, dtype=''int64'')
print(c*d) # 没有溢出:[50000000000]

好了,前面提出的问题就回答完了。来作个结尾吧:

  • Python 3 极大地简化了整数的表示,效果可表述为:整数就只有一种整数(int),没有其它类型的整数(long、int8、int64 之类的)
  • Numpy 中的整数类型对应于 C 语言的数据类型,每种“整数”有自己的区间,要解决数据溢出问题,需要指定更大的数据类型(dtype)

公众号【Python猫】, 本号连载优质的系列文章,有喵星哲学猫系列、Python进阶系列、好书推荐系列、技术写作、优质英文推荐与翻译等等,欢迎关注哦。

"import numpy as np" ImportError: No module named numpy

问题:没有安装 numpy

解决方法:

下载文件,安装

numpy-1.8.2-win32-superpack-python2.7

安装运行 import numpy,出现

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    import numpy
  File "C:\Python27\lib\site-packages\numpy\__init__.py", line 153, in <module>
    from . import add_newdocs
  File "C:\Python27\lib\site-packages\numpy\add_newdocs.py", line 13, in <module>
    from numpy.lib import add_newdoc
  File "C:\Python27\lib\site-packages\numpy\lib\__init__.py", line 8, in <module>
    from .type_check import *
  File "C:\Python27\lib\site-packages\numpy\lib\type_check.py", line 11, in <module>
    import numpy.core.numeric as _nx
  File "C:\Python27\lib\site-packages\numpy\core\__init__.py", line 6, in <module>
    from . import multiarray
ImportError: DLL load failed: %1 不是有效的 Win32 应用程序。

原因是:python 装的是 64 位的,numpy 装的是 32 位的

重新安装 numpy 为:numpy-1.8.0-win64-py2.7

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

3.7Python 数据处理篇之 Numpy 系列 (七)---Numpy 的统计函数

3.7Python 数据处理篇之 Numpy 系列 (七)---Numpy 的统计函数

目录

[TOC]

前言

具体我们来学 Numpy 的统计函数

(一)函数一览表

调用方式:np.*

.sum(a) 对数组 a 求和
.mean(a) 求数学期望
.average(a) 求平均值
.std(a) 求标准差
.var(a) 求方差
.ptp(a) 求极差
.median(a) 求中值,即中位数
.min(a) 求最大值
.max(a) 求最小值
.argmin(a) 求最小值的下标,都处里为一维的下标
.argmax(a) 求最大值的下标,都处里为一维的下标
.unravel_index(index, shape) g 根据 shape, 由一维的下标生成多维的下标

(二)统计函数 1

(1)说明

(2)输出

.sum(a)

.mean(a)

.average(a)

.std(a)

.var(a)

(三)统计函数 2

(1)说明

(2)输出

.max(a) .min(a)

.ptp(a)

.median(a)

.argmin(a)

.argmax(a)

.unravel_index(index,shape)

作者:Mark

日期:2019/02/11 周一

Anaconda Numpy 错误“Importing the Numpy C Extension Failed”是否有另一种解决方案

Anaconda Numpy 错误“Importing the Numpy C Extension Failed”是否有另一种解决方案

如何解决Anaconda Numpy 错误“Importing the Numpy C Extension Failed”是否有另一种解决方案?

希望有人能在这里提供帮助。我一直在绕圈子一段时间。我只是想设置一个 python 脚本,它将一些 json 数据从 REST API 加载到云数据库中。我在 Anaconda 上设置了一个虚拟环境(因为 GCP 库推荐这样做),安装了依赖项,现在我只是尝试导入库并向端点发送请求。 我使用 Conda(和 conda-forge)来设置环境并安装依赖项,所以希望一切都干净。我正在使用带有 Python 扩展的 VS 编辑器作为编辑器。 每当我尝试运行脚本时,我都会收到以下消息。我已经尝试了其他人在 Google/StackOverflow 上找到的所有解决方案,但没有一个有效。我通常使用 IDLE 或 Jupyter 进行脚本编写,没有任何问题,但我对 Anaconda、VS 或环境变量(似乎是相关的)没有太多经验。 在此先感谢您的帮助!

  \Traceback (most recent call last):
File "C:\Conda\envs\gcp\lib\site-packages\numpy\core\__init__.py",line 22,in <module>
from . import multiarray
File "C:\Conda\envs\gcp\lib\site-packages\numpy\core\multiarray.py",line 12,in <module>
from . import overrides
File "C:\Conda\envs\gcp\lib\site-packages\numpy\core\overrides.py",line 7,in <module>
from numpy.core._multiarray_umath import (
ImportError: DLL load Failed while importing _multiarray_umath: The specified module Could not be found.

During handling of the above exception,another exception occurred:

Traceback (most recent call last):
File "c:\API\citi-bike.py",line 4,in <module>
import numpy as np
File "C:\Conda\envs\gcp\lib\site-packages\numpy\__init__.py",line 150,in <module>
from . import core
File "C:\Conda\envs\gcp\lib\site-packages\numpy\core\__init__.py",line 48,in <module>
raise ImportError(msg)
ImportError:

IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!

Importing the numpy C-extensions Failed. This error can happen for
many reasons,often due to issues with your setup or how NumPy was
installed.

We have compiled some common reasons and troubleshooting tips at:

https://numpy.org/devdocs/user/troubleshooting-importerror.html

Please note and check the following:

* The Python version is: python3.9 from "C:\Conda\envs\gcp\python.exe"
* The NumPy version is: "1.21.1"

and make sure that they are the versions you expect.
Please carefully study the documentation linked above for further help.

Original error was: DLL load Failed while importing _multiarray_umath: The specified module Could not be found.

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

Difference between import numpy and import numpy as np

Difference between import numpy and import numpy as np

Difference between import numpy and import numpy as np

up vote 18 down vote favorite

5

I understand that when possible one should use

import numpy as np

This helps keep away any conflict due to namespaces. But I have noticed that while the command below works

import numpy.f2py as myf2py

the following does not

import numpy as np
np.f2py #throws no module named f2py

Can someone please explain this?

python numpy

shareimprove this question

edited Mar 24 ''14 at 23:20

mu 無

24.7k104471

asked Mar 24 ''14 at 23:19

user1318806

3001311

 
1  

@roippi have you tried exit your python and enter it and just do import numpy then numpy.f2py ? It throws an error in my case too – aha Mar 24 ''14 at 23:24

1  

Importing a module doesn''t import sub-modules. You need to explicitly import the numpy.f2py module regardless of whether or not/how numpy itself has been imported. – alecb Mar 24 ''14 at 23:39

add a comment

4 Answers

active oldest votes

 

up vote 13 down vote

numpy is the top package name, and doing import numpy doesn''t import submodule numpy.f2py.

When you do import numpy it creats a link that points to numpy, but numpy is not further linked to f2py. The link is established when you do import numpy.f2py

In your above code:

import numpy as np # np is an alias pointing to numpy, but at this point numpy is not linked to numpy.f2py
import numpy.f2py as myf2py # this command makes numpy link to numpy.f2py. myf2py is another alias pointing to numpy.f2py as well

Here is the difference between import numpy.f2py and import numpy.f2py as myf2py:

  • import numpy.f2py
    • put numpy into local symbol table(pointing to numpy), and numpy is linked to numpy.f2py
    • both numpy and numpy.f2py are accessible
  • import numpy.f2py as myf2py
    • put my2py into local symbol table(pointing to numpy.f2py)
    • Its parent numpy is not added into local symbol table. Therefore you can not access numpy directly

shareimprove this answer

edited Mar 25 ''14 at 0:31

answered Mar 24 ''14 at 23:33

aha

1,2291718

 

add a comment

 

up vote 7 down vote

The import as syntax was introduced in PEP 221 and is well documented there.

When you import a module via

import numpy

the numpy package is bound to the local variable numpy. The import as syntax simply allows you to bind the import to the local variable name of your choice (usually to avoid name collisions, shorten verbose module names, or standardize access to modules with compatible APIs).

Thus,

import numpy as np

is equivalent to,

import numpy
np = numpy
del numpy

When trying to understand this mechanism, it''s worth remembering that import numpy actually means import numpy as numpy.

When importing a submodule, you must refer to the full parent module name, since the importing mechanics happen at a higher level than the local variable scope. i.e.

import numpy as np
import numpy.f2py   # OK
import np.f2py      # ImportError

I also take issue with your assertion that "where possible one should [import numpy as np]". This is done for historical reasons, mostly because people get tired very quickly of prefixing every operation with numpy. It has never prevented a name collision for me (laziness of programmers actually suggests there''s a higher probability of causing a collision with np)

Finally, to round out my exposé, here are 2 interesting uses of the import as mechanism that you should be aware of:

1. long subimports

import scipy.ndimage.interpolation as warp
warp.affine_transform(I, ...)

2. compatible APIs

try:
    import pyfftw.interfaces.numpy_fft as fft
except:
    import numpy.fft as fft
# call fft.ifft(If) with fftw or the numpy fallback under a common name

shareimprove this answer

answered Mar 25 ''14 at 0:59

hbristow

68345

 

add a comment

 

up vote 1 down vote

numpy.f2py is actually a submodule of numpy, and therefore has to be imported separately from numpy. As aha said before:

When you do import numpy it creats a link that points to numpy, but numpy is not further linked to f2py. The link is established when you do import numpy.f2py

when you call the statement import numpy as np, you are shortening the phrase "numpy" to "np" to make your code easier to read. It also helps to avoid namespace issues. (tkinter and ttk are a good example of what can happen when you do have that issue. The UIs look extremely different.)

shareimprove this answer

answered Mar 24 ''14 at 23:47

bspymaster

760923

 

add a comment

 

up vote 1 down vote

This is a language feature. f2py is a subpackage of the module numpy and must be loaded separately.

This feature allows:

  • you to load from numpy only the packages you need, speeding up execution.
  • the developers of f2py to have namespace separation from the developers of another subpackage.

Notice however that import numpy.f2py or its variant import numpy.f2py as myf2py are still loading the parent module numpy.

Said that, when you run

import numpy as np
np.f2py

You receive an AttributeError because f2py is not an attribute of numpy, because the __init__() of the package numpy did not declare in its scope anything about the subpackage f2py.

shareimprove this answer

answered Mar 24 ''14 at 23:57

gg349

7,67321739

 
    

when you do import numpy.f2py as myf2py, how do you access its parent numpy? it seems import numpy.f2py allows you to access its parent numpy, but import numpy.f2py as myf2py doesn''t – aha Mar 25 ''14 at 0:00

    

You don''t access it because you decided you didn''t want to use anything from numpy, and you only care of using the subpackage. It is similar to using from foo import bar: the name foo will not be accessible. See the comment after the first example of the docs, LINK – gg349 Mar 25 ''14 at 0:05

add a comment

我们今天的关于Python 的整数与 Numpy 的数据溢出python整数溢出问题的分享就到这里,谢谢您的阅读,如果想了解更多关于"import numpy as np" ImportError: No module named numpy、3.7Python 数据处理篇之 Numpy 系列 (七)---Numpy 的统计函数、Anaconda Numpy 错误“Importing the Numpy C Extension Failed”是否有另一种解决方案、Difference between import numpy and import numpy as np的相关信息,可以在本站进行搜索。

本文标签: