A_V
A_V

Reputation: 109

ValueError: negative number cannot be raised to a fractional power in iterable list - Python

We have a list of 10 points of coord. x and y as follow:

NOTE: Here we iterate through the lists of x,y and br without using numpy.array because in the far future, I will replicate this into 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]

NOTE: rad_cut is the radius of the circle (r^2 = x^2 + y^2) rad_cut = input("Please provide a value of 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

The issue I have having is as follows:

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

I would appreciate if anyone can lend me a hand to resolve this issue. I have tried to use complex numbers because of the negative number in the iterable lists x[i+0j]**0.5 + y[i+0j]**0.5 < rad_cut: but it didn't work.

Upvotes: 0

Views: 788

Answers (1)

PM 2Ring
PM 2Ring

Reputation: 55499

As noted in the comments you need to square those x & y values, rather than taking their square roots.

Here's a more Pythonic way to write your program. This code will work on Python 2.6 and up, it will also work properly on Python 3.

The main change is that it uses a generator expression inside the sum() function to add the appropriate br values.

#!/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))

typical output

      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

Note: It's better in Python 2 to use raw_input() rather than input(), since the Python 2 version of input() uses the potentially dangerous eval() function on the entered data; the Python 3 version of input() is identical to Python 2's raw_input().

Upvotes: 3

Related Questions