How to create a program to calculate a polynomial in python? - python

So this is the directions to my homework:
Write a program to calculate a polynomial. The program should ask for
the user for a,b,c, and x. It should ouput the value of ax^2+ bx +c by
calling a function named CalcPoly(a,b,c,x) that returns the value of
the function to the main program. The main program should print, not
the function.
And this is what I have so far:
def CalcPoly(a, b, c, x):
print ("Enter the first degree: ")
print (int(input(a)))
print ("Enter the second degree: ")
print (int(input(b)))
print ("Enter the third degree: ")
print (int(input(c)))
print (a*x**2 + b*x + c)
CalcPoly()
And the error I got was:
Traceback (most recent call last):
File "main.py", line 14, in <module>
CalcPoly()
TypeError: CalcPoly() missing 4 required positional arguments: 'a', 'b', 'c', and 'x'
I don't know how to fix it and I don't even know if I did the code right. I would appreciate any assistance. Thank you so much!

Try this:
def CalcPoly(a, b, c, x):
print (a*x**2 + b*x + c)
if __name__=="__main__":
a = int(input("Enter the first degree: "))
b = int(input("Enter the second degree: "))
c = int(input("Enter the third degree: "))
CalcPoly(a, b, c, 4) # x=4
# Console:
# Enter the first degree: 1
# Enter the second degree: 2
# Enter the third degree: 3
# 27

Since you say that the main program should print and not the function, you may try this.
def CalcPoly(a, b, c, x):
result = (a*x**2) + (b*x) + c
return result
a = int(input("Enter the coefficient of x^2 (a): "))
b = int(input("Enter the coefficient of x (b): "))
c = int(input("Enter the constant (c): "))
x = int(input("Enter x :"))
value = CalcPoly(a, b, c,x)
print(value)
Also you were facing an issue with your code, that is -
TypeError: CalcPoly() missing 4 required positional arguments: 'a', 'b', 'c', and 'x'
This is because while defining the CalcPoly() function you have declared 4 positional arguments a, b, c and x and while calling the function you haven't given the values of a, b, c and x in the function call.

The function CalcPoly expects the arguments of the polynomial coefficients and the value of variable x.
You can call the function correctly as follows:
CalcPoly(1,2,3,4)
This will evaluate the equation as x^2 + 2x + 3 where x=4.
But, if you are reading inputs, you must define function as follows:
def CalcPoly()
And also, please do not forget to read input for the value of x.

There are a lot of things wrong in your code.
First, the reason for the error itself-
def CalcPoly(a, b, c, x):
This takes in 4 arguments, a, b, c, and x, you pass none of them when calling the function-
CalcPoly()
Now, that is far from the end of the story. In python you take input like this-
a = int(input())
This gets user input and stores it into a. I'm assuming that's what you wanted to do, any argument within the parens of input() means that will be printed as a prompt-
a = int(input("Enter the first degree: "))
This will prompt the user,
Enter the first degree:
then wait for user input, turn it into an int and store it inside a
All the other input should be the same.
Your question says you should be taking input for a, b, c, and x, not just a, b, c.
So your fixed up function should look like-
def CalcPoly(a, b, c, x):
a = int(input("Enter the first degree: "))
b = int(input("Enter the second degree: "))
c = int(input("Enter the third degree: "))
x = int(input("Enter the x value: "))
print(a*x**2 + b*x + c)
This is really basic stuff, you should read the python docs tutorial

I'd like to add an object-oriented approach here. Let's create a class where the method get_input collects inputs from users and the method __call__ basically performs the polynomial calculation. This way you can separate the process of data collection and the actual calculation.
from typing import Union
class CalcPoly:
def get_input(self):
a: int = int(input("Enter the first degree:"))
b: int = int(input("Enter the second degree:"))
c: int = int(input("Enter the third degree:"))
x: Union[int, float] = input("Enter x:")
return a, b, c, x
def __call__(self):
a, b, c, x = self.get_input()
return (a*x**2) + (b*x) + c
calc = CalcPoly()
print(calc())

Related

Solving Monomial and Polynomial Python Class

I am experimenting with classes for the first time, and I wanted to create a program that asks the user for an input a,b, and c, and then solves for x for the equation forms stated in the print statements. However, I am having issues with the class, giving me an error that I am not using the variables in the class, missing the 5 positional arguments. Any help would be amazing, thanks so much.
class EquationSolver:
def MonomialSolver(self,a,b,c,x):
a = input("Enter Input for a:")
b = input("Enter Input for b:")
c = input("Enter input for c:")
x = (c+b)/a
print("For the equation in the format ax-b=c, with your values chosen x must equal", x)
def PolynomialSolver(self,a,b,c,x):
a = input("Enter Input for a:")
b = input("Enter Input for b:")
c = input("Enter input for c:")
x = (c^2 + b) / a
print("For the equation in the format sqrt(ax+b) = c, with your values chosen x must equal", x)
MonomialSolver()
PolynomialSolver()
The problem I see is the inputs for the functions. You do not need the self parameter or any other parameter. The functions should run outside the loop. The edited version should loop something like this:
class EquationSolver:
def MonomialSolver():
# Uses float() to turn input to a number
a = float(input("Enter Input for a:"))
b = float(input("Enter Input for b:"))
c = float(input("Enter input for c:"))
x = (c+b)/a
print("For the equation in the format ax-b=c, with your values chosen x must equal", x)
def PolynomialSolver():
a = float(input("Enter Input for a:"))
b = float(input("Enter Input for b:"))
c = float(input("Enter input for c:"))
x = (c^2 + b) / a
print("For the equation in the format sqrt(ax+b) = c, with your values chosen x must equal", x)
EquationSolver.MonomialSolver()
EquationSolver.PolynomialSolver()

python linear equation with Cramer's rule

I'm new to python and attempting to write a linear equation using Cramer's Rule. I've entered the formula and have code prompting user to enter a,b,c,d,e and f but my code is getting a syntax error. I'd like to fix the code and also have a system for researching and correcting future errors.
a,b,c,d,e,f = float(input("Enter amount: ")
a*x + by = e
cx + dy = f
x = ed-bf/ad-bc
y=af-ed/ad-bc
if (ad - bc == 0)print("The equation has no solution")
else print ("x=" x, "y=" y,)
Basically, your code was one giant syntax error. Please read some basic tutorial, as was suggested in the comments. Hopefully this will help in the learning process (I didn't go through the actual math formulas):
a = float(input("Enter a: "))
b = float(input("Enter b: "))
c = float(input("Enter c: "))
d = float(input("Enter d: "))
e = float(input("Enter e: "))
f = float(input("Enter f: "))
##a*x + by = e
##cx + dy = f
if (a*d - b*c == 0):
print("The equation has no solution")
else:
x = (e*d-b*f)/(a*d-b*c)
y = (a*f-e*d)/(a*d-b*c)
print ("x=%s" % x, "y=%s" % y)
You have to put * between the numbers you want to multiply. You had one parenthesis missing from your input statement. The equations themselves are commented out, because otherwise Python takes them as a code (incorrectly written one). You have to enclose the denominator in parentheses because math. You have to end the if, else, elif, for, while and such with :. Indentation is VERY important in Python.

Accessing the variable of a function within a function

So say I have the lower value and an upper value of an integral that's from the user input. I ask for the lower limit first then I check for its validity. Then in order to compare the value of my upper limit with my lower I made a nested function, so that I can also ask for user input of the upper limit, checks its validity and making sure that my upper limit is bigger than my lower(cuz u know integration), shown with the code below.
def LowLimCheck():
while True:
try:
a = float(input("Please enter the lower limit of the integral: "))
break
except ValueError:
print("Invalid input. Please enter a number.")
print("You have chosen the lower limit: ", a)
def UppLimCheck():
b = -1
while b <= a:
while True:
try:
b = float(input("Please enter the upper limit of the integral: "))
break
except ValueError:
print("Invalid input. Please enter a number.")
if b <= a:
print("The upper limit must be bigger than the lower limit!")
print("You have chosen the upper limit: ", b)
return b
UppLimCheck()
return a
Now this is all well and fine until I actually need to use the values a and b because I need to put those values into an integral that I've set up. It's basically a general integral made by the Simpson's rule, that is trivial to get into right now. So I defined the function as:
def simpsonsRule(func, a, b, N):
<insert code here>
<insert code here>
return d
OK so my function basically lets user insert any arbitrary function, the upper limit(a), the lower limit(b) and N(number of strips in Simpson's rule) and it spits out d which is the evaluation of the integral of the arbitrary function above by Simpson's Rule. My problem now is that when I'm trying to print the answer, I can take the variable a out and put in into the integral but I can't take the variable b out because it's in a function! For example if I now print the integrated value(say in this case of sin(x) and N = 20)
print(simpsonsRule(lambda x:np.sin(x), a, b, 20)
So I know that a and b values are local within their own functions. Now for the value of a I could easily just do this to get the value a
k = 0 #initialising the variable
k = LowLimCheck()
print(simpsonsRule(lambda x:np.sin(x), k, b, 20)
Because since k invokes LowLimCheck() which returns the value for a which I can put into my function. But how can I get my value of b which is nested within the first function? I want to use b basically. Is there a way round this?
Apologies for the lengthy question and thanks in advance!
You can return a tuple from LowLimCheck():
def LowLimCheck():
...
b = UppLimCheck()
return (a,b)
then unpack them when calling LowLimCheck()
a, b = LowLimCheck()
UPDATE:
In the most direct answer to your question, LowLimCheck() becomes:
def LowLimCheck():
while True:
try:
a = float(input("Please enter the lower limit of the integral: "))
break
except ValueError:
print("Invalid input. Please enter a number.")
print("You have chosen the lower limit: ", a)
def UppLimCheck():
b = -1
while b <= a:
while True:
try:
b = float(input("Please enter the upper limit of the integral: "))
break
except ValueError:
print("Invalid input. Please enter a number.")
if b <= a:
print("The upper limit must be bigger than the lower limit!")
print("You have chosen the upper limit: ", b)
return b
b = UppLimCheck() # Storing the b
return (a,b) # Passing b out with a in a tuple
then call
a, b = LowLimCheck()
finally,
print(simpsonsRule(lambda x:np.sin(x), a, b, 20)
ALTERNATIVE SOLUTION (more substantial changes, but better code structure - as described in the original comments; flatter, more readable, fewer scope considerations):
def LowLimCheck():
while True:
try:
a = float(input("Please enter the lower limit of the integral: "))
break
except ValueError:
print("Invalid input. Please enter a number.")
print("You have chosen the lower limit: ", a)
return a
def UppLimCheck(a):
b = -1
while b <= a:
while True:
try:
b = float(input("Please enter the upper limit of the integral: "))
break
except ValueError:
print("Invalid input. Please enter a number.")
if b <= a:
print("The upper limit must be bigger than the lower limit!")
print("You have chosen the upper limit: ", b)
return b
then:
lowLim = LowLimCheck()
upLim = UppLimCheck(lowLim) # pass in lowLim as an argument
print(simpsonsRule(lambda x:np.sin(x), lowLim, upLim, 20)

Euler's Method Python Variable Input Type

I'm having an issue with the following code. It's currently in progress but a large problem that I'm running into is that my input of a function returns an error no matter what type of input I have tried. It either returns with an issue with the error type, or an issue of x not being defined if I enter a function such as x.
f = raw_input("Please enter function: y' = ")
x0 = float(raw_input("Please enter the initial x value: "))
y0 = float(raw_input("Please enter the initial y value: "))
xmax = float(raw_input("Please enter the value of x at which to approximate the solution: "))
h = float(raw_input("Please enter the step size: "))
showall = int(raw_input("Would you like to see all steps (1) or only the approximate solution (2)? "))
def f(x,y):
value = f
return (value)
def euler(x0,y0,h,xmax):
x=x0; y=y0; xd=[x0]; yd=[y0];
while x<xmax:
y = y + h*f(x,y)
yd.append(y)
x=x+h
xd.append(x)
return(xd,yd)
(xvals,yvals) = euler(x0,y0,h,xmax)
if showall == 1:
print ""
print "x_n y_n"
for uv in zip(xvals, yvals):
print uv[0],uv[1]
elif showall == 2:
print ""
print "x_n y_n"
print xvals, yvals
else:
print ""
print "There has been an error with your choice of what to see; showing all steps."
print ""
print "x_n y_n"
for uv in zip(xvals, yvals):
print uv[0],uv[1]
print " "
plotask = int(raw_input("Would you like to see a plot of the data? Yes (1); No (2) "))
if plotask == 1:
print "1"
elif plotask == 2:
pass
else:
print ""
print "Could not understand answer; showing plot."
Any help would be appreciated.
The error and trace is the following:
File "C:\Users\Daniel\Desktop\euler.py", line 25, in <module>
(xvals,yvals) = euler(x0,y0,h,xmax)
File "C:\Users\Daniel\Desktop\euler.py", line 19, in euler
y = y + h*f(x,y)
TypeError: unsupported operand type(s) for *: 'float' and 'function'
This function:
def f(x,y):
value = f
return (value)
Can be seen to return a function. In particular, it does nothing except return itself, f. (note that f is different from f() or f(x,y)
y = y + h*f(x,y)
evaluates to
y = y + h*f
which is an error, as f is a function and you cannot multiply a function by a number (as opposed to the RESULT of evaluating a function call - e.g. if f(x,y) returns a number, then your code will work)
The issue you're having is that your function f is using the same name as the formula string you're collecting in the first line of your code. However, just fixing the name won't do what you want, I don't think.
Your f function will need to evaluate the formula, in order to get a numeric result. I think you want this:
formula = raw_input("Please enter function: y' = ")
def f(x, y):
return eval(formula)
While this works, I do want to point out that using eval is generally not recommended practice, especially when the string you're evaluating comes from a user. That's because it can include arbitrary Python code, which will be run. eval('__import__(os).system("rm -Rf *")') could really ruin your day (don't run this code!).

Keep getting syntax error. What do I need to do?

I am trying to get my function to take two arguments, and return their sum. Am I going about this the right way? This is what I have so far:
def my_sum(a, b):
sum = a + b
def main():
a = input(int("enter a number: ", a)
b = input(int("enter a number: ", b)
sum = a + b
return sum
print(" result: ", sum)
main()
So it looks good, but the main problem is that you aren't actually calling your function :) Once you get your two numbers, you can then make the call to your function (which you have properly set up):
def main():
# When you assign variables here, make sure you are putting the int outside
# You also don't need to reference the variable twice
a = int(input("enter a number: "))
b = int(input("enter a number: "))
# Here is where your call goes (try to avoid using variable names that
# are the same as Python keywords, such as sum)
s = my_sum(a, b)
print(" result: ", s)
Now, one other thing you'll have to do is modify your function to return a value. You're already almost there - just add a return (note that since you are just returning the sum of the two numbers, you don't have to assign it to a variable):
def my_sum(a, b):
return a + b
This now means that when you run s = my_sum(a, b), your function will return the sum of those two numbers and put them into s, which you can then print as you are doing.
One other minor thing - when you use the setup you are (with def main(), etc.), you usually want to call it like this:
if __name__ == '__main__':
main()
At this stage, don't worry too much about what it means, but it is a good habit to get into once you start getting into fun stuff like modules, etc. :)
You Have written Wrong coding Style
If you want to do some by using sum method than do this
def my_sum(a, b):
sum = a + b
return sum
def main():
a = int(raw_input("enter a number: "))
b = int(raw_input("enter a number: "))
sum = my_sum(a,b)
print" result: ", sum
main()
I hope this will work as per your requirement.
Regards,
Anil
I am not sure of the purpose of the first function you have defined there (my_sum). However, there are a few things wrong in main as well. The return function always exits the function it is in, and zooms out to a higher level scope. This is very similar to break, except that it returns a value as well. Also, your syntax when you ask for user input is incorrect. It should be:
def main():
a = int(raw_input("Enter a number: "))
b = int(raw_input("Enter a number: "))
return "Result" + (a+b)
main()
Also, if you wanted my_sum to automatically return the sum, you should use return or print:
def my_sum(a, b):
return a + b
doing a print function after return sum won't work because when returning a return value, the execution will exit the scope, the orders should be reversed.
your input function is not implemented correctly.
The correct code should be:
def main():
a = input("enter a number: ")
b = input("enter a number: ")
sum = a + b
print(" result: ", sum)
return sum

Categories

Resources