Dzmitrij Pasat
Dzmitrij Pasat

Reputation: 1

Math formula in Python

So I have this math formula that has two inputs (two numbers that you have to plug in, positive integers). The names for the terms are "diagonal" and "term (n)". The equation is

( n(n+1)(n+2)...(n+ (diagonal-2)) )/ (diagonal-1)!

So essentially you plug in two numbers (diagonal, and term) and it should spit out a number. So I wrote a program in python, but it always returns 0.

import math

diagonal = input("What diagonal do you want to see?")

term = input("What term do you want to see?")

product= term
for i in range (term + (diagonal - 2)):

    product = ((product * (i+1))/(math.factorial(diagonal - 1)))

print(product)

To test this when you plug in number 4 for both the term and diagonal you should get 20.

EDIT: I tried the different methods posted and now it return 80 when 4,4 is plug in. import math

diagonal = input("What diagonal do you want to see?")
term = input("What term do you want to see?")

product= float(term)
for i in range (term, term + (diagonal - 2)+1):
    product = (product * (i))

product /= math.factorial(diagonal - 1)
print product

Upvotes: 0

Views: 249

Answers (3)

pzp
pzp

Reputation: 6597

Here's a functional approach to your problem.

from operator import mul

product = lambda lo, hi: reduce(mul, xrange(lo, hi))
formula = lambda n, d: product(n, n+d-1)/product(1, d)

print formula(4, 4)

20

EDIT
The problem with your code is that you are multiplying by the initial value of term twice (hence why you are getting 80 instead of 20 when the term and diagonal are both 4). To fix this change the line product= float(term) to product = 1.

Upvotes: 0

David Hoelzer
David Hoelzer

Reputation: 16331

Your algorithm is incorrect, especially when dividing by the factorial.

If you are sure that is what you want to do, you may want to make product a float or you will always get zero since your first divide is less than 1...

product = float(term)

Upvotes: 1

Greg Hewgill
Greg Hewgill

Reputation: 992757

I don't think you want to divide by the factorial for every iteration. Do that after your loop.

for i in range (term + (diagonal - 2)):
    product = product * (i+1)
product /= math.factorial(diagonal - 1)

Upvotes: 4

Related Questions