Dániel Terbe
Dániel Terbe

Reputation: 105

Creating normal distribution in python

I try to create a normal distribution in python. I made the following code:

    prior = []
    variance = 20
    mean = 0.5
    x = -100

    while x <= 100:
            normal_distribution = 1/np.sqrt(1*np.pi*variance*variance)*np.exp(np.power(x-mean,2)/(2*variance*variance))
            prior.extend(normal_distribution)
            ++x

But I got a type error:

TypeError: 'numpy.float64' object is not iterable

I tried that the normal_distribution = ... Has a value outside the while loop. I don't exactly understand why it can't iterate.

Upvotes: 2

Views: 493

Answers (3)

decltype_auto
decltype_auto

Reputation: 1736

TypeError: 'numpy.float64' object is not iterable

As far as I see, normal_distribution is scalar-valued, thus it'd be prior.append(normal_distribution), not prior.extend(normal_distribution) .

Btw - appending in a loop is not performance-friendly, let alone idiomatic.

Better use a generator expression like

prior = [(f(x) for x in range(-100, 101)]

where f is the function or lambda you use to generate your data.

Upvotes: 0

Shawn Mehan
Shawn Mehan

Reputation: 4568

You don't want to extend. If you go and look at the doc for extend you'll find

class list(object)  
def extend(self, t) Inferred type: (self: list[T], t: Iterable[T]) -> None   L.extend(iterable) -- extend list by appending elements from the utterable

so you can now see why your code fails. It is indeed trying to iterate the object that you pass to extend, and, as you rightly point out, it can't. so, boom!

What you want is append

class list(object)  

def append(self, x) Inferred type: (self: list[T], x: T) -> None   L.append(object) -- append object to end

Changing this will lead you to the next exciting part of the debugging process, determining why your loop is infinite :) Good luck

Upvotes: 0

lejlot
lejlot

Reputation: 66775

There are three problems:

  1. You are looking for .append, not .extend; this is the source of the error, as .extend requires iterable object as an argument, so it can append each of its elements to the list. You are adding a single element - this is what .append is for
  2. Your equation for pdf is invalid, you should have

    • 2 instead of 1 under the square root
    • negation inside exp
    • your variance variable is used in the meaning of std

    1/np.sqrt(2*np.pi*variance)*np.exp(-(x-mean)**2/(2*variance))

  3. There is no such thing as ++x in python, use x += 1

Upvotes: 3

Related Questions