0

I am trying to solve this exercise from a course I found online. (if you recognize the question, tell me what you think about the course). I have looking on how to solve this, but I keep having bugs on my computation and I think it is mostly because I am not certain on how the output will be as well as how to write certain parts of the function. I'll humbly take any kind explanation and advice, there is still a long way to go for me so I"llbe around.

Here is the question,

The Legendre polynomials are defined by:

()=∑=0(−1)(2−2)!2!(−)!(−2)!−2

where =/2 if n is even or (−1)/2 if is odd. ! means "the factorial of m", for example, 4! = 1 * 2 * 3 * 4 = 24. You can compute it like this: from math import factorial factorial(4) 24

Here is a helpful function to compute :

import numpy as np
def M(n):
    if np.mod(n, 2) == 0:  # this means n is even.
        return int(n / 2)
    else:
        return int((n - 1) / 2)

Write a function that computes P(x, n), and plot the function for n=3 and n=4 on the range of x=-1 to x=1.

import scipy as sp
P_tot = []
x = np.linspace(-1,1,10)
n = [3,4]
def P(x,n):
    return ((-1)**M(n))*((factorial(2*n-2*M(n)))/((2**n)*factorial(M(n))*factorial(n-M(n))*factorial(n-2*M(n))))*(x**(n-2*M(n)))
x = np.linspace(-1,1,10)
n = [3,4]
Px,pn = P(x,n)
P_tot += [Px,pn]

ValueError Traceback (most recent call last ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I can't wait to see how easy it was and was I missed out.

Thanks for your time.

Bill Hileman
  • 2,798
  • 2
  • 17
  • 24
  • You are passing `n = [3, 4]` to `if np.mod(n, 2) == 0`. What did you expect is the result of that? – mkrieger1 Mar 12 '20 at 19:58
  • Does this answer your question? [NumPy ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()](https://stackoverflow.com/questions/22175489/numpy-valueerror-the-truth-value-of-an-array-with-more-than-one-element-is-ambi) – mkrieger1 Mar 12 '20 at 19:59
  • The usual way to write `M(n)` would be just `n//2` (assuming that `n` is an int or a NumPy array with integer dtype). That's not going to work if `n` is a list of ints, though; convert to a NumPy array first if you really want to work with multiple `n` at once. (Though it's probably easier to keep `n` a scalar throughout and generate the plots for `n=3` and `n=4` in two separate calls.) – Mark Dickinson Mar 14 '20 at 12:03

0 Answers0