Python Forum

Full Version: Multiplicate several numbers
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello!

I have this function:
1 + 1/x^2

I want to get the product of this function from n = 1 to n = 19
(1 + 1/1^2) * (1 + 1/2^2) * (1 + 1/3^2) * (1+1/n^2)....

How can I do this in python in a easy way?
I get the right numbers but i cant figure out how to multiplie all togheter.

Python script so far:

n = 1

while n < 19:
n = n + 1
func = (1 + 1/n**2)
print(func)
Start with func = 1 before the loop, and then each time you calculate the new value, do func *= calculated_value to multiply it into the rolling total.

Edit:
Or, if you write your function as a function, you can use map/reduce to do the same thing much cleaner:
>>> import functools
>>> import operator
>>> def func(x):
...   return 1 + (1/(x**2))
...
>>> functools.reduce(operator.mul, map(func, range(1, 19)))
3.482783207792457
Thanks for answer, but it didnt work :/
Do you have other suggestions? :)

[Image: kCqm92f]
Don't post images. Copy/paste the code in python tags. If you get any errors, post the full traceback in error tags. All that said, what you show in the image has nothing common with the nilamo's suggestion/advice
(Oct-05-2018, 08:40 AM)Student0 Wrote: [ -> ]Thanks for answer, but it didnt work :/
Do you have other suggestions? :)

[Image: kCqm92f]
Well, the code by nilamo:
import functools
import operator

def func(x):
    return 1 + (1/(x**2))

print(functools.reduce(operator.mul, map(func, range(1, 19))))
worked for me.

Output:
3.482783207792457
(Oct-05-2018, 08:40 AM)Student0 Wrote: [ -> ]Thanks for answer, but it didnt work :/
Do you have other suggestions? :)

[Image: kCqm92f]

Please just share code in the future. If you had done so, pretty much anyone could have told you what the issue was lol.
You're overwriting func when you do func = something. Instead, multiply it by itself, like func = func * something, or, using the shorthand, func *= something.

I'll type your code here, so it isn't just in the picture:
Quote:
n = 1
func = 1

while n < 19:
    n = n + 1
    calculated_value = func * func
    func = (1 + 1/n**2)
    print(func)

print(func)
print("Calculated Value = ", calculated_value)