How do I fix this OverflowError? - python

I keep getting a "OverflowError: math range error". No matter what I input, the result is the same. I'm running Python 3.3, and it's finding the problem at the last line. How do I fix this? (Also, I don't want to hear anything about my overuse of parentheses. It is my preference for there to be this many.):
import math
a=float(input('a=?'))
b=float(input('b=?'))
c=float(input('c=?'))
d=float(input('d=?'))
critical_point_n=((-2*b)-math.sqrt(abs((4*(math.pow(b, 2)))-(12*a*c))))/(6*a)
first_root=critical_point_n-1
if first_root==0 and c==0:
first_root+=(-0.01)
for x in range(10):
first_root=first_root-((a*(math.pow(first_root, 3)))+(b*(math.pow(first_root, 2))+(c*first_root)+d)/(3*(a*(math.pow(first_root, 2))))+(2*(b*first_root))+c)

I know you don't want to hear about your excessive use of parenthesis, but the problem is that you have the parenthesis in the wrong places. With the sheer number of parenthesis you used, it took a while to find the problem.
I think the following code is much cleaner, easier to debug, and vastly easier to maintain in the future. I also included what I think is the corrected version of your one-liner.
import math
a=float(input('a=?'))
b=float(input('b=?'))
c=float(input('c=?'))
d=float(input('d=?'))
critical_point_n=((-2*b)-math.sqrt(abs((4*(math.pow(b, 2)))-(12*a*c))))/(6*a)
first_root=critical_point_n-1
if first_root==0 and c==0:
first_root+=(-0.01)
for x in range(10):
f = a*first_root**3 + b*first_root**2 + c*first_root + d
fp = 3*a*first_root**2 + 2*b*first_root + c
first_root = first_root - (f/fp)
#first_root=first_root-(((a*(math.pow(first_root, 3)))+(b*(math.pow(first_root, 2))+(c*first_root)+d)))/((3*(a*(math.pow(first_root, 2))))+(2*(b*first_root))+c)
print(first_root)

You are overflowing the internal representation of floats. Use sys.float_info to check your system's limits for floating point numbers. http://docs.python.org/3.3/library/sys.html#sys.float_info
I recommend trying out your operations by "hand" on wolframalpha to see the magnitude of the actual values. http://www.wolframalpha.com/

The math range of functions work on doubles... so you're out of range for that - re-write as normal Python floats which will scale as needs be, or look at using decimal.Decimal which also has sqrt, power etc.. functions: http://docs.python.org/2/library/decimal.html

Related

how to get real valule in R [duplicate]

I'm just learning R, so please forgive what I'm sure is a very elementary question. How do I take the real part of a complex number?
If you read the help file for complex (?complex), you will see a number of functions for performing complex arithmetic. The details clearly state
The functions Re, Im, Mod, Arg and Conj have their usual interpretation as returning the real part, imaginary part, modulus, argument and complex conjugate for complex values.
Therefore
Use Re:
Re(1+2i)
# 1
For the imaginary part:
Im(1+2i)
# 2
?complex will list other useful functions.
Re(z)
and
Im(z)
would be the functions you're looking for.
See also http://www.johnmyleswhite.com/notebook/2009/12/18/using-complex-numbers-in-r/

Solve single variable equation using if, else and while statements in python

I am tutoring a 7th grade student in basic programming and mathematics. One of the problems the students needs to complete for a class assignment is "create a program to solve a given single variable linear equation". The student is required to use python and only use if, else and while statements. The program can include user defined functions and lists but cannot import any libraries like regex, sympy, numpy, etc.
The program should be able to solve these example equations:
2*x - 5 = 8
4*x + 3 = 3*x - 10
11*x = 2 - (1/5)*x
4*(x + 2) = 5*(x + 9)
I tried: For each character in the string note the numerals, operators, equals to sign and variable. Copy the variable and its coefficient into a new string and the constants with their signs to another string. My hope was that I would eventually extract the integers from each string and solve the equation for x. But I wasn't correctly capturing numbers with multiple digits. And the equation with parentheses completely stumped me. Not being able to use regex or sympy is painful!
I am looking for a pythonic solution to this problem if it exists.
I feel this is a very difficult question for a 7th grader because my grad and undergrad friends haven't been able to come up with a solution. Any advice on how to proceed will help if a programmatic solution isn't available.
Thank you.
Although it is completely possible to build a finite automaton solve an expression, it is not an easy task.
I myself had lots of assignments related to build a semantic or syntax parser, but it is usually done in C: https://codereview.stackexchange.com/questions/112620/simple-expression-calculator-in-c.
Nonetheless, if you accept a clever/dangerous/bad-practice solution:
def solve_expression(expr, var="x"):
expr = expr.replace(var, "1j")
left, right = map(eval, expr.split("="))
return (right.real-left.real)/(left.imag-right.imag)
print(solve_expression("2*x - 5 = 8"))
print(solve_expression("4*x + 3 = 3*x - 10"))
print(solve_expression("11*x = 2 - (1/5)*x"))
print(solve_expression("4*(x + 2) = 5*(x + 9)"))
The idea is to convert the free variable to the imaginary unit and let python interpreter do the rest.

Math programming with python

So I'm pretty new to programming and I don't understand how to do this problem.
Egg cartons each hold exactly 12 eggs. Write a program which reads an integer number of eggs from input(), then prints out two numbers: how many cartons can be filled by these eggs, and how many eggs will be left over. I would really appreciate the help!
At first, what you are looking for is the modulo operator and the function math.floor()
Modulo
from wikipedia:
In computing, the modulo operation finds the remainder after division of one number by another (sometimes called modulus).
for example:
12%12=0
24%12=0
25%12=1
this does fit your needs for the eggs that are leftover.
Math.floor()
returns the largest following integer.
eg.:
Math.floor(13/2)
would be the same as
Math.floor(6.5)
and result in 6.
This function should solve your problem with the fully filled egg cartons.
Hint
remember to import floor() properly.
from math import floor
First, try to figure the rest out on your own.
You shouldn't look at this until your code is done.
Either way I'm not your mom, if you wanna die dumb I tried to prevent it.
https://github.com/AiyionPrime/EggCartons
One last thing.
It does not matter wether your attempts to solve a problem were stupid or failed hard.
But if you ever expect an answer to one of your problems you should explain what you tried.
We're not here to solve your problems, but to help you understand to do it.
I remember that text. It comes from a site for exercising with Python coding.
Its name is Computer Science Circles, if I remember correctly.
Anyway, the correct answer at that specific exercise is:
eggs = input() #Reads imput, assigning it to the "eggs" variable
eggs = int(eggs) #Converts the "eggs" variable into an int
print(eggs // 12) #Performs a division, showing the result and ignoring the remainder, giving you the exact number of cartons that can be filled by the "eggs" variable
print(eggs % 12) #Performs a second division, this time showing only the remainder, giving you the exact number of eggs that will be left over

Is Python reevaluating arithmetic operations with bignums each time the resut is used?

Okay, I was trying to throw in some really large number evaluation on python - of the order of 10^(10^120)- which i then realized was quite huge. Anyways, I then receded to 10**10**5 and 10**10**6. Checking the time difference of the two brought me to this somewhat strange finding which I could see as an inefficiency.
The finding was that when I tried cProfile.run("x=10**10**6") it took 0.3s and cProfile.run("print 10**10**6") took 40s.
Then I tried x= 10**10**6 which took almost no time but thereafter every time that I interpreted x (x followed by enter) it would take a really long time (40s I suppose). So, I am assuming that every time that I interpret x it calculates the entire value over again.
So my question is: isn't that extremely inefficient? Say I had declared some variable in a module, x= 10**10, and every time I would reference x the python interpreter would compute the value of 10**10 over and over again ?
Gory details would be much appreciated.
Python can calculate extremely large numbers using binary, but to turn that back into digits that can be displayed is a lot of work.
For example: (and what quite a few Euler projects ask) -
What is the sum of all the digits of, say, 2 ** 32768
Python can use BigNum's to calculate that result as a number pretty much straight anyway, but as soon as you do:
sum(int(c) for c in str(my_big_number)) # ouch - that's a lot of digits to produce and store
So that's what's happening when you type (then press enter) the variable name/print the variable name, it's performing a conversion.
The value is not being recalculated each time you print it, the long delay you see is the cost of converting the large number into a string for displaying.

Python std.stdout.write loop problems

I'm not sure of what's going on here, but I have some python code:
import sys
max_cols = 350
max_rows = 1
r1 = range(max_rows)
r2 = range(max_cols)
for y in r1:
for x in r2:
sys.stdout.write('something')
if x is not max_cols-1:
sys.stdout.write(',')
Now, this works fine for values of max_cols <= 257.
However, if you use >= 258, you end up with an extra ',' at the end.
(The idea here is obviously to generate a CSV file.)
Now, 256 is a CS number, so there's clearly something going on here that I'm unaware of, since everything works perfectly up until that point. This also happens when I try to write to a file using the same pattern.
Why does this happen?
Using Python 3.2.
is is not for checking equality but for checking identity. x is y is only true if both variables refer to the same object. As it happens, CPython resuses objects for small integers - but in general, the concept of identity is very different from the concept of equality. Use the correct operators, == and != for equality and inequality respectively, and it works.
Also note that the code can be made much simpler and robust by just using the csv module. No need to reinvent the wheel.
The CPython implementation caches small numbers, so all instances of the number 12 are the same object. The is operator compares the identities of objects, not their values. What you wanted to do was use the != operator to compare the values.
It's likely that your instance of the CPython implementation caches numbers up to 256.
Incidentally, whenever you bump into a pattern like this, where you have to drop the last separator from a list of delimited things, str.join is probably what you wanted.

Categories