简体   繁体   English

Python numpy 数组数学显示奇怪的结果

[英]Python numpy array math showing weird results

The last cell of the bellow array shows a wrong result:波纹管数组的最后一个单元格显示错误的结果:

Code:代码:

import numpy
b=numpy.array ([[1,2,3,4],[5,6,8,16]])
b=b**b/b+1
b

result:结果:

array([[2.000000e+00, 3.000000e+00, 1.000000e+01, 6.500000e+01],
       [6.260000e+02, 7.777000e+03, 2.097153e+06, 1.000000e+00]])

All numbers are correct except for the last one.除最后一个数字外,所有数字都是正确的。

Type is numpy.float64 .类型是numpy.float64 The correct answer is 1.152921504606847e+18 .正确答案是1.152921504606847e+18

Any ideas?有任何想法吗?

Thanks谢谢

When you construct a numpy array with whole numbers, its type will be int32 or int64 depending on your system, instead of the float64 you expected.当您使用整数构造numpy数组时,其类型将是int32int64 ,具体取决于您的系统,而不是您期望的float64 So when you do 16**16 , the result overflowed and you end up with a 0.因此,当您执行16**16时,结果会溢出,最终得到 0。

To fix this, specify the float64 type for your numpy array, like this:要解决此问题,请为 numpy 数组指定float64类型,如下所示:

b=numpy.array ([[1,2,3,4],[5,6,8,16]], dtype='float64')

Or if you want, add a .0 to any of the numbers in your array to specify that you want to use float not int.或者,如果您愿意,可以将.0添加到数组中的任何数字,以指定您要使用 float 而不是 int。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM