【问题标题】:ValueError: negative number cannot be raised to a fractional power in iterable list - PythonValueError:负数不能提高到可迭代列表中的分数幂 - Python
【发布时间】:2015-07-31 07:53:39
【问题描述】:

我们有一个包含 10 个坐标点的列表。 x 和 y 如下:

注意:这里我们在不使用 numpy.array 的情况下遍历 x、y 和 br 的列表,因为在遥远的将来,我会将其复制到 Fortran77 中。

x = [7., -6., 7., -7., 8., 9., 5., 4., -5., 0.]
for i, x[i] in enumerate(x):
  print 'The values of x =', x[i]


y = [3., 6., 3., 9., 1., 9., -2., 0., 3., 7.]
for i, y[i] in enumerate(y):
  print 'The values of y =', y[i]


br  = [1., 2., 8., 0., 7., 9., 6., 9., 7., 4.]
for i, br[i] in enumerate(br):
   print 'brightness = ',br[i]

注意:rad_cut 是圆的半径 (r^2 = x^2 + y^2) rad_cut = input("请提供rad_cut的值:")

 br_total = 0
 for i in xrange(0,10):
    if x[i]**0.5 + y[i]**0.5 < rad_cut:
       br_total += br[i]

 print 'The total brightness = ', br_total

我遇到的问题如下:

 in <module>
    if x[i]**0.5 + y[i]**0.5 < rad_cut:
ValueError: negative number cannot be raised to a fractional power

如果有人能帮我解决这个问题,我将不胜感激。由于可迭代列表中的负数x[i+0j]**0.5 + y[i+0j]**0.5 &lt; rad_cut:,我尝试使用复数 但它没有用。

【问题讨论】:

  • 你当然应该做if (x[i]**2 + y[i]**2)**0.5 &lt; rad_cut?或者更有效的是,rad_sq = rad_cut**2 ... if (x[i]**2 + y[i]**2) &lt; rad_sq
  • @skyking:你是对的。谢谢,我的程序现在可以运行了!
  • @Arvind.R 错误源于数学问题。与自身相乘的数字永远不会产生负数(即两个负数相乘成为正数),因此负数的平方根在技术上是不可能的。 ** 0.5 本质上就是平方根,导致这个 ValueError。

标签: python arrays negative-number


【解决方案1】:

如 cmets 中所述,您需要对这些 x 和 y 值求平方,而不是取它们的平方根。

这是编写程序的更 Pythonic 方式。此代码适用于 Python 2.6 及更高版本,也适用于 Python 3。

主要变化是它在sum() 函数中使用generator expression 来添加适当的br 值。

#!/usr/bin/env python
from __future__ import print_function

x = [7., -6., 7., -7., 8., 9., 5., 4., -5., 0.]
y = [3., 6., 3., 9., 1., 9., -2., 0., 3., 7.]
br = [1., 2., 8., 0., 7., 9., 6., 9., 7., 4.]

print('      x    y   br')
for i, (xi, yi, bri) in enumerate(zip(x, y, br)):
    print('{0}: {1:4.1f} {2:4.1f} {3:4.1f}'.format(i, xi, yi, bri))

rad_cut = input("Please provide a value of rad_cut: ")
rad_cut = float(rad_cut)

rad_sq = rad_cut ** 2

br_total = sum(bri for xi, yi, bri in zip(x, y, br) 
    if xi**2 + yi**2 < rad_sq)

print('The total brightness = {0:.1f}'.format(br_total))

典型输出

      x    y   br
0:  7.0  3.0  1.0
1: -6.0  6.0  2.0
2:  7.0  3.0  8.0
3: -7.0  9.0  0.0
4:  8.0  1.0  7.0
5:  9.0  9.0  9.0
6:  5.0 -2.0  6.0
7:  4.0  0.0  9.0
8: -5.0  3.0  7.0
9:  0.0  7.0  4.0
Please provide a value of rad_cut: 10
The total brightness = 44.0

注意:在 Python 2 中最好使用raw_input() 而不是input(),因为input() 的Python 2 版本在输入的数据上可能使用dangerous eval() function; Python 3 版本的 input() 与 Python 2 的 raw_input() 相同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-13
    • 1970-01-01
    • 1970-01-01
    • 2018-07-12
    • 2021-09-09
    • 2015-11-17
    • 1970-01-01
    • 2013-12-02
    相关资源
    最近更新 更多