Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Solving equation - Overflow error

Tags:

equation

sympy

Basically I just want to solve k. Note that the equation equals to 1.12

import math
from sympy import *

a = 1.45
b = 4.1
c = 14.0

al = math.log(a, 2)
bl = math.log(b, 2)
cl = math.log(c, 2)

k = symbols('k')

print solve(Eq(1/k**al + 1/k**bl + 1/k**cl, 1.12), k)

This raises OverflowError: Python int too large to convert to C long

Solution using other libraries welcomed too.

like image 860
nutship Avatar asked May 15 '26 05:05

nutship


2 Answers

Since you are using numerical values, I am assuming that you are looking for a numerical solution. In that case, you should not use solve, because it tries to find a symbolic solution. The issue here is that it converts these floating point exponents into rational exponents, which have very large numerators and denominators, and it then at some point tries to make polynomials of degree corresponding to those large numbers, which is where it fails.

To solve numerically, you can use nsolve.

>>> print nsolve(Eq(1/k**al + 1/k**bl + 1/k**cl, 1.12), 2)
1.82427203413783

It's better to use numeric libraries like SciPy if you are interested in numeric solutions, though. You can use lambdify to convert your SymPy expressions into functions more suited for libraries like SciPy that use NumPy arrays.

like image 85
asmeurer Avatar answered May 17 '26 17:05

asmeurer


It is a known issue.

You may try

solve(Eq(1/k**al + 1/k**bl + 1/k**cl, 1.12), k, rational=False)
like image 27
zs2020 Avatar answered May 17 '26 18:05

zs2020