0

I am new at coding and I am trying to plot the fallowing function.
H_n(x)=Sum((-1.)^(k)(N!))/((k)!(N-2.k)!)((2.*x)^(N-2.*k)) where k=0->(N/2) and N is an integer that is defined by the user.
I get the fallowing error: TypeError: unsupported operand type(s) for ** or pow(): 'float' and 'function'
Here is my code I've done thus far.

from matplotlib.pyplot import plot, show
import numpy as np
import math


N = input('define N: ')
def factorial(N):
    if N <= 1:
        return 1
    else:
        return N * factorial(N-1)


def k(N):
    s = 0

    for i in np.arange(0,N/2):
        s += 1
    return k
def binomial(N,k):
    b = ((-1.)**(k)*factorial(N))/(factorial(k)*factorial(N-2.*k))*((2.*x)**(N-2.*k))
    return b


x=np.arange(-4,4,.1)
plot(binomial(N,k))
show()

I have tested my factorial function and it does find a factorial of an input. I just cannot figure out where I am going wrong.

Adam_T
  • 1
  • 4
    In `(-1.)**(k)`. you're raising a float (`-1.`) to the power of a function `k`. Understandably, Python complains. Perhaps you meant to call `binomial` with arguments `N` and `k(N)` rather than `N` and `k`? – Mark Dickinson Feb 01 '16 at 09:37
  • There are further issues: 1) In function `k(N)` you probably want to return `s` instead of the function itself. 2) Why define `x` when you never use it? Don't you want to plot the function over `x`? – hitzg Feb 01 '16 at 09:53
  • 1
    In addition to the above two comments, it would also help a lot if you could clean up the formatting of the original equation. In particular - in mathematical notation - is the term within the sum supposed to be `-1 ^ (k*N!)` or `(-1^k)*N!` – J Richard Snape Feb 01 '16 at 09:55
  • BTW, the `math` module has a factorial function that's much faster than calculating factorial yourself. See [here](http://stackoverflow.com/a/28477818/4014959) for some timing data. However, calculating binomial coefficients using factorials is generally inefficient. See [my answer](http://stackoverflow.com/a/26561091/4014959) for both factorial-based & non-factorial binomial coefficient functions. – PM 2Ring Feb 01 '16 at 12:13
  • As others have implied, using `k` as the name of a function and as the name of a variable is both confusing and error-prone. But your `k()` function doesn't make sense. It returns a value of `k` but never defines `k`. – PM 2Ring Feb 01 '16 at 12:16

0 Answers0