Chance Gordon
Chance Gordon

Reputation: 143

How to fix TypeError: unsupported operand question

I'm writing a function in Python product_z which computes the product of (N^z)/z * ∏ k/z+k from k=1 to N.

The code looks like this;

import numpy as np

def z_product(z,N):
    terms = [k/(z+k) for k in range(1,N+1)]
    total = (N^z/z)*np.prod(terms)
    return total

However, I'm running the code with this input for example but I get a TypeError in return.

"Check that z_product returns the correct datatype."
assert type(z_product(2,7)) == np.float64 , "Return value should be a NumPy float."
print("Problem 2 Test 1: Success!")
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-9-d2e9161f328a> in <module>()
      1 "Check that z_product returns the correct datatype."
----> 2 assert type(z_product(2,7)) == np.float64 , "Return value should be 
a NumPy float."
      3 print("Problem 2 Test 1: Success!")

<ipython-input-8-1cd27b06388f> in z_product(z, N)
      1 def z_product(z,N):
      2     terms = [k/(z+k) for k in range(1,N+1)]
----> 3     total = (N^z/z)*np.prod(terms)
      4     return total

TypeError: unsupported operand type(s) for ^: 'int' and 'float'

What am I doing wrong and how do I fix this to make the code run?

Upvotes: 0

Views: 36

Answers (1)

sacuL
sacuL

Reputation: 51335

I think you're trying to exponentiate using the ^ operator. This is the proper operator in some languages (like R or MATLAB), but is not proper python syntax. In Python, the ^ operator stands for XOR. Use ** instead:

def z_product(z,N):
    terms = [k/(z+k) for k in range(1,N+1)]
    total = (N**z/z)*np.prod(terms)
    return total

>>> z_product(2,7)
0.6805555555555555

Alternatively, you can use np.power intead:

def z_product(z,N):
    terms = [k/(z+k) for k in range(1,N+1)]
    total = (np.power(N,z)/z)*np.prod(terms)
    return total

Upvotes: 1

Related Questions