Python Forum
Multiplicate several numbers
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Multiplicate several numbers
#1
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)
Reply
#2
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
Reply
#3
Thanks for answer, but it didnt work :/
Do you have other suggestions? :)

[Image: kCqm92f]
Reply
#4
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
(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
I am trying to help you, really, even if it doesn't always seem that way
Reply
#6
(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)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Print Numbers starting at 1 vertically with separator for output numbers Pleiades 3 3,661 May-09-2019, 12:19 PM
Last Post: Pleiades

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020