My Python Equation Solver Can't Solve for Fractions - python

Ok, so I made a small equation solver that solves for x. It works great for integer values, but whenever I try to solve for fractions it goes into an endless loop. Here is my code:
print "Make the variable in your equation stand for x"
print
startingLimit=int(raw_input("What is the lowest estimate that your variable could possibly be?"))
print
wholeNumber=raw_input("Do you know if your variable will be a whole number or a fraction? Answer: yes/no")
if (wholeNumber== "yes"):
print
fraction= raw_input("Is it a decimal/fraction? Answer:yes/no")
if (fraction=="yes"):
print
print "This program will only calculate up to the 2nd place to the right of the decimal"
xfinder=float(0.01)
else:
xfinder=int(1)
else:
xfinder=float(0.01)
leftEquation=raw_input("Enter your left side of the equation:")
print
rightEquation=raw_input("Enter the right side of the equation:")
print
amountSolutions=100
print
#solving
a=0
indivisualCount=0
count=0
x=float(startingLimit)
while (count!=amountSolutions):
ifstuffleft=eval(leftEquation)
ifstuffright=eval(rightEquation)
if (ifstuffleft!=ifstuffright):
x=float(x+xfinder)
print x
else:
a=(a+1)
count=count+1
print "Solution",a,"=",x
print
x=float(x+xfinder)

if (ifstuffleft!=ifstuffright): should become
if abs(ifstuffleft - ifstuffright) < tolerance:
Where tolerance is the error you're willing to accept

Related

simple python program doesnt run. shows intendent error

I'm trying to fix a problem like if a number is odd or even. this is a simple program to find if a number is odd or even
x=input("enter x")
if x%2==0:
print "even"
else
print "odd"
shows indented error in line 3.
plz help
okay, first of all -
you haven't formatted your code properly. Use the shortcut ctrl+K to do so when you're posting a question. I assume this is what you're looking for:
x = input("Enter X")
if x % 2 == 0:
print "Even"
else:
print "Odd"

Python: Printing something changes the outcome?

So I'm new to this programming thing... But this has me stumped. To the point that I'm wondering if the website I'm running Python on is wrong. (repl.it is the website).
So I did one of those guess the number games as a small fun challenge. This is the code that I came up with:
from random import randint
print ("Welcome to guess the number!")
answer = str(randint(0,100))
print (answer)
print ()
def something():
answerTwo = str(randint(0,100))
print (answerTwo)
idea(answerTwo)
def idea(x):
number = str(input("Guess a number between 0 and 100:"))
if number != x:
if (number > x):
print()
print(number + " is too high!")
print()
idea(x)
elif (number < x):
print()
print(number + " is too low!")
print()
idea(x)
else:
print()
print ("That is correct!")
again = input("Would you like to play again?:")
if again == "yes":
something()
else:
print ("Thanks for playing!")
idea(answer)
On the 4th and 8th line I print out the random number chosen so that I can quickly test to make sure everything works. Then I removed the print functions in the final product and tested again. Except when I removed the print functions it stopped working after some amount of time. For example, it'll say 39 is too low but 40 is too high, which is impossible since they're is no number in between them. If you put the print functions back in it works again, but remove them and it'll start acting up eventually.
I apologize if it's something really obvious but I just don't understand how this is possible.
Here is the github thingy for it
https://gist.github.com/anonymous/4a370664ae8ddb29aec5915eb20e686f
Thanks for your time!
There is no integer i such that 39 < i < 40.
There is however a numeric string s such that "39" < s < "40". Observe:
>>> "39" < "4" < "40"
True
In short: It has nothing to do with your print calls, instead, just work on actual numbers and cast your input to a number using int(). print() can handle numbers just fine.

How to implement a numeric guessing game with loops in Python

So I'm creating this game where the computer guesses a number, and based on the reply, it splits and re-selects a number. I've had little problems so far, but now I'm quite stuck on the loop. I know what I have to do, I just can't figure out how to do it properly, and have it function.
lowest = int(input( "What is the lowest number you will think of?: "))
highest = int(input( "What is the highest number you will think of?: "))
print("So you're thinking of a number between",lowest,"and",highest)
x=[]
for number in range(lowest,highest):
x.append(number)
middleIndex = (len(x))//2
print ("is it "+str(x[middleIndex])+"?")
answer = input("")
if answer == "lower":
x = (x[:len(x)//2])
else:
x = (x[len(x)//2:])
I know it has to go after the
x.append(number)
but I can't get it to work using for or while loops.
The entire for loop is kind of pointless, with the x.append line especially so. range() gives you a list anyway (in Python 3 it gives you a range object which can be converted to a list using the list function).
You could replace that with:
x=list(range(lowest, highest))
Also, this is more convention than anything technically incorrect, but in Python I think camel case is generally reserved for class names; for this reason, I would rename middleIndex to middle_index.
And finally, you don't have anything for the case when the computer guesses the right number!
What you're looking for is basically an interactive binary search algorithm that runs over a range of numbers. You don't actually need to use range or a list, because you can calculate the average of your min and max values instead of finding the middle_index.
Here is an example implementation:
def main():
print("What range will your guessed number fall within?")
min = int(input("Min: "))
max = int(input("Max: "))
print("Ok; think of a number between {0} and {1}.".format(min, max))
while min <= max:
mid = (min + max) // 2
if input("Is it {0}? (Y/N) ".format(mid)) == "Y":
print("It is!? Well, that was fun.")
return
elif input("Darn. Is it higher than {0}? (Y/N) ".format(mid)) == "Y":
min = mid + 1
else:
max = mid - 1
print("Well, it looks like you were dishonest somewhere along the line.")
print("I've exhausted every possibility!")
main()

Returning else statement regardless if If conditions met in Python [duplicate]

This question already has an answer here:
Python - Weird IF statement while using nested lists
(1 answer)
Closed 5 years ago.
##---Initializing Variable----------------------------------------------------------------------#
#-----------------------------------------------------------------------------------------------#
objectMass=0
weight=0
##---Introductory Statement: Welcome to the Program---------------------------------------------#
#-----------------------------------------------------------------------------------------------#
def intro():
print("\n".join(["---------------------------------------------------------",
"Hello and Welcome to Mass to Weight Calculator",
"Today is a good day!",
"---------------------------------------------------------"]))
##---The getMass module gets user input for mass & stores in getMass reference modules----------#
#-----------------------------------------------------------------------------------------------#
def getMass():
objectMass=float(input("Please enter the Mass of the object you want calculated: "))
return objectMass
##--The weightConversion module calculates inputted mass into weight----------------------------#
#-----------------------------------------------------------------------------------------------#
def weightConversion(objectMass):
gravity = 9.8
weight=float(objectMass)*gravity
return weight
##--Calculation Module compares weight of object and prints out sentence associated to weight---#
#-----------------------------------------------------------------------------------------------#
def massToWeight(objectMass, weight):
if weight > 1000:
print("\n".join(["Holy Smokes, your weight(in newtons) is:", format(weight, ".2f"),
"It's way too heavy!!!"]))
if weight < 10:
print("Aww man, I can pick this up with one finger.", "It's way too light!",
"This weight(in newtons) is:", format(weight, ".2f"))
else:
print("This weight(in newtons):", format(weight, ".2f"), "is just right.")
return
##---Closing Statement--------------------------------------------------------------------------#
#-----------------------------------------------------------------------------------------------#
def closingStatement():
print("\n".join(["---------------------------------------------------------",
"Thank you for using our Mass to Weight Calculator!",
"Please use us for all your calculation needs."]))
return
##---Main module--------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------------------------#
def main():
##Introductory Statement
intro()
##---Get Mass
objectMass=getMass()
##Calculate Mass to Weight
weight=weightConversion(objectMass)
##Compare results
massToWeight(objectMass, weight)
##Closing Statement
closingStatement()
main()
Hey everyone. My program is returning my else when my first condition of > 1000 is met in the massToWeight module and not sure why. The program didn't need modules, but wanted to practice working with modules in python.
Could someone please help?
Thank you,
Darryl
if weight > 1000: #IF1
print()
if weight < 10: #IF2
print()
else:
print()
The problem is that the IF2 should have been elif
Let's consider an example:
Let weight = 10000
The IF1 condition will pass and it will get executed.
Now, since, IF2 is not elif, this will be treated as a totally separate new If-else statement.
The IF2 condition will fail and then it's else part will get executed.
use
elif weight < 10:
instead of
if weight < 10:

Issues with while loop

So this code is meant to return the final error and the final logarithm of a number inputted by a user. Now my issue is that it doesn't run the loop, it just keeps going over the same number and it never ends. I am not sure if I have my print statements in the wrong area, or if I am doing the loop wrong but I want the loop to end when the error is less then 1x10^-9. It's possible my iterations are set up wrong too, not really sure what I messed up on here.
import math
import sys
#Computing natural log of x
#x value is input here
x = float(input("Please input a positive number: "))
#If x is not positive then program will not work, so it will exit
if x<=0:
print("Your number is not positive. System Shutdown.")
sys.exit()
#Retrieving ln(x) using the math command
lnx0 = math.log(x)
#Formula for approximate ln
xfrac = (x - 1)/(x + 1)
lnx = 0 #Initializing the approximating
i=0
#This is the code to make it go until it hits the error we want
while True:
ex = 2*i - 1
lnx += 2.0* (xfrac**ex / ex)
#Counter adding 1 to it
i+=1
#This is the error
err = math.fabs(lnx0 - lnx)
if err<0.0000000001:
break
#Priting approximate ln at end of loop
print ("ln(x) at " ,x,"is: " ,lnx)
#Final Error
print ("Final error is:" ,err)
#Number of itterations
#Printing accurate version of ln(x) just to see what it should be
print ("Your accurate value of ln(x) is: " ,lnx0)
I'm assuming you're using the fourth formula on this page to approximate the log function. If so, your i is starting at the wrong value; you've initialized it to 0 here, but it needs to start at 1.
Also, if you only want output after the answer has been found, rather than once per iteration, your print functions should be de-indented so they are outside the loop. Try:
import math
import sys
#Computing natural log of x
#x value is input here
x = float(input("Please input a positive number: "))
#If x is not positive then program will not work, so it will exit
if x<=0:
print("Your number is not positive. System Shutdown.")
sys.exit()
#Retrieving ln(x) using the math command
lnx0 = math.log(x)
#Formula for approximate ln
xfrac = (x - 1)/(x + 1)
lnx = 0 #Initializing the approximating
i=1
#This is the code to make it go until it hits the error we want
while True:
ex = 2*i - 1
lnx += 2.0* (xfrac**ex / ex)
#Counter adding 1 to it
i+=1
#This is the error
err = math.fabs(lnx0 - lnx)
if err<0.0000000001:
break
#Priting approximate ln at end of loop
print ("ln(x) at " ,x,"is: " ,lnx)
#Final Error
print ("Final error is:" ,err)
#Number of itterations
#Printing accurate version of ln(x) just to see what it should be
print ("Your accurate value of ln(x) is: " ,lnx0)
Result:
Please input a positive number: 5
ln(x) at 5.0 is: 1.6094379123624052
Final error is: 7.169509430582366e-11
Your accurate value of ln(x) is: 1.6094379124341003
Thanks to DSM for identifying the formula and possible fix
There are several problems with this. The first is that your computations are incorrect. I tried entering 'e' to 9 places. Your estimate, lnx, quickly degenerates to -3.3279+ and sticks there. This dooms you to an infinite loop, because the estimate will never get near the true value.
Others have already pointed out that you haven't traced your computations with print statements. I'll add another hint from my days in numerical analysis: use a restricted "for" loop until you've debugged the computations. Then trade it in for a "while err > tolerance" loop.
To address your most recent comment, you're not getting the same numbers. The first few terms are significant, but the infinite sequence quickly drops close to 0, so the additions don't show up after about 15-20 iterations.
Also print out ex and lnx values within the loop. Especially check the first one, where your exponent is -1; I believe that you've started the loop in the wrong place.
Finally, you might find this loop form a little easier to read. Get rid of your if...break statement and use this instead:
i = 1
err = 1
tolerance = 1e-10
# This is the code to make it go until it hits the error we want
while err >= tolerance:

Categories