python linear equation with Cramer's rule - python

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.

Related

Writing a program to find sum of a series using math.pow and math.factorial

Here is the question my teacher gave us:
Write a program to find the sum of the following series (accept values of x and n from user). Use functions of the math library like math.pow and math.factorial:
1 + x/1! + x2/2! + ……….xn/n!
This is the code I've come up with. I calculated it on paper with simple numbers and there's clearly some logic errors because I can't get a correct answer. I think I've been looking at it for too long to really grasp the issue, so I could use some help.
import math
x = int(input ("Input x: "))
n = int(input("Input n: "))
for i in range (n):
power = math.pow(x,i)
ans = 1 + (power / math.factorial(i))
print(ans)
Note: This is an entry level class, so if there's an easier way to do this with a specific function or something I can't really use it because I haven't been taught it yet, although appreciate any input!
I would not recommend using those functions. There are better ways to do it that are within the grasp of entry level programmers.
Here's what I recommend you try:
import math
x = int(input ("Input x: "))
n = int(input("Input n: "))
sum = 1
term = 1.0
for i in range (1,n+1):
term *= x/i
sum += term
print(sum)
You don't need those functions. They're inefficient for this case.
I believe the following will work for you:
import math
x = int(input ("Input x: "))
n = int(input("Input n: "))
ans = 1
for i in range (1,n+1):
power = math.pow(x,i)
ans += (power / math.factorial(i))
print(ans)
We start the ans variable at 1 and we add the new term to ans through each iteration of the loop. Note that x+=n is the same as x=x+n for integers.
I also changed the range that your loop is going through, since you start at 1 and go up to n, rather than starting at 0 and going to n-1.
Output:
Input x: 2
Input n: 5
7.266666666666667
For people familiar with the mathematical constant e:
Input x: 1
Input n: 15
2.718281828458995
Your ans only includes (the 1 and) the latest term. You should instead Initialize it before the loop and then add all the terms to it. The first term 1 doesn't deserve ugly special treatment, so I compute it like all the others instead:
import math
x = int(input ("Input x: "))
n = int(input("Input n: "))
ans = 0
for i in range(n + 1):
ans += math.pow(x, i) / math.factorial(i)
print(ans)
And a preview how you'll likely soon be taught/allowed to write it:
import math
x = int(input ("Input x: "))
n = int(input("Input n: "))
print(sum(math.pow(x, i) / math.factorial(i)
for i in range(n + 1)))

This Python code for quadratic equation isn't working

I'm trying to get the userinput for a,b,c using a function and it doesn't seems to work
import math
def equationroots():
try:
a = int(input("Enter the coefficients of a: "))
b = int(input("Enter the coefficients of b: "))
c = int(input("Enter the coefficients of c: "))
except ValueError:
print("Not a number!")
my = b * b - 4 * a * c
sqrt_val = math.sqrt(abs(my))
quadratic = (-b + sqrt_val)/(2 * a)
return quadratic
print("The equation root of the numbers is" quadratic)
equationroots()
You have not used the proper intents, This is what your code supposed to be.
import math
def equationroots():
try:
a = int(input("Enter the coefficients of a: "))
b = int(input("Enter the coefficients of b: "))
c = int(input("Enter the coefficients of c: "))
except ValueError:
print("Not a number!")
my = b * b - 4 * a * c
sqrt_val = math.sqrt(abs(my))
quadratic = (-b + sqrt_val)/(2 * a)
return quadratic
quadratic = equationroots()
print("The equation root of the numbers is", quadratic)
Indentation is very important in Python to separate block statements. It appears your indentation is off, leading to some lines not being executed when you intend.
For example, the variables my, sqrt_val, and quadratic are only calculated if the except label is reached. This means they are only attempted to be calculated if there is an input error, which wouldn't work anyways.
It's possible you also pasted in your code and the formatting was adjusted, and that isn't the issue. If that is the case, please edit the question to reflect the formatting and indentation you are using.
You need to fix your indentations from the except portion. Indentations are very important in python
fix this portion:
except ValueError:
print("Not a number!")
my = (b*b)-(4*a*c)
sqrt_val = math.sqrt(abs(my))
quadratic = ((-b)+sqrt_val)/(2*a)
return quadratic
then call your function first then use that to print your statement. Like,
quadratic = equationroots()
print(f"The equation root of the numbers is {quadratic}")

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

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!).

Python program that wont terminate

I'm running the following code from the command line (python filename.py) and it wont terminate. I've tried the code outside of a procedure and have tried the procedure in an online interpreter, so I don't think it's the the algorithm. What am I doing wrong?
n = raw_input("Enter a number: ")
def print_multiplication_table(n):
x = 1
while x <= n:
y = 1
while y <= n:
z = x * y
print x, " * ", y, " = ", z
y += 1
x += 1
print_multiplication_table(n)
You should convert the number received from raw_input into an integer. Right now it's being compared as a string.
An easy (but probably bad) way to do this:
n = int(raw_input("Enter a number: "))
There is a problem with the raw_input command. I have a similar code myself (guess we're both following the Udacity course). I tried to add the raw_input line to my code, and it ended up in an infinite loop too.

Categories

Resources