How to make a binomial expansion solver in python?

In this blog post I will make a binomial expansion solver which will expand equations in the form with integer indices:


Plan

  • Inputs
  • Binomial expansion

Maths

It is important to understand the maths before you begin programming.

This is the binomial expansion formula
This finds out how many combinations of
n entities if you choose r entities.
Click this link for more information on the maths.

Inputs

print("(a+bX)^c")
A=int(input('a = '))
B=int(input('b = '))
C=int(input('c = '))

This tells the user what the values represent and it records the user’s numbers


Binomial expansion

x=2
expansion=str(A**C)+' + '+str(B*C)+'x'
while x<(C+1):
    nCr=(math.factorial(C))/((math.factorial(x))*(math.factorial(C-x)))
    expansion=expansion+' + '+str((B**x)*int(nCr))+'x^'+str(x)
    x=x+1
print(expansion)

This creates an expansion and prints it.

expansion=str(A*C)+’ + ‘+str(BC)+’x’

This produces the first 2 terms. I did these separate so you don’t get x^0 and x^1 as it makes it appear more confusing to a user.


nCr=(math.factorial(C))/((math.factorial(x))*(math.factorial(C-x)))

This uses the nCr equation by using the math.factorial() from the math module.


while x<(C+1):
nCr=(math.factorial(C))/((math.factorial(x))(math.factorial(C-x))) expansion=expansion+’ + ‘+str((Bx)int(nCr))+’x^’+str(x)
x=x+1

This makes the terms as long as necessary.


Full code

#Imports
import math

#Inputs
print("(a+bX)^c")
A=int(input('a = '))
B=int(input('b = '))
C=int(input('c = '))

#Binomial Expansion
x=2
expansion=str(A**C)+' + '+str(B*C)+'x'
while x<(C+1):
    nCr=(math.factorial(C))/((math.factorial(x))*(math.factorial(C-x)))
    expansion=expansion+' + '+str((B**x)*int(nCr))+'x^'+str(x)
    x=x+1
print(expansion)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s