Python Forum
Multiplicate several numbers - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Multiplicate several numbers (/thread-13226.html)



Multiplicate several numbers - Student0 - Oct-04-2018

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)


RE: Multiplicate several numbers - nilamo - Oct-04-2018

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



RE: Multiplicate several numbers - Student0 - Oct-05-2018

Thanks for answer, but it didnt work :/
Do you have other suggestions? :)

[Image: kCqm92f]


RE: Multiplicate several numbers - buran - Oct-05-2018

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


RE: Multiplicate several numbers - gruntfutuk - Oct-05-2018

(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



RE: Multiplicate several numbers - nilamo - Oct-09-2018

(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)