0

I have small problem with too big float numbers in Python. Overflow errors occur.

The function look like this:

N(t + 1) = (1 + c) N(t) - (c / d) * N(t)**2 where t is time, and c and d are constants.

I need it to calculate up to one minute (t = 60). But after t= 8, 9 or 10 I got overflow error.

def nValue(t):
    n_calc = []
    c = 2.3 # 0..3
    d = 95  # 1..250
    n_0 = 450 # 0..600
    n_1 = (1 + c) * n_0 - c / d * n_0**2
    n_calc.append(n_0)
    n_calc.append(n_1)
    for i in range(2, t+1):
        n_curr = (1 + c) * n_calc[i- 1] - (c / d) * (n_calc[i- 1]**2)
        n_calc.append(n_curr)

    return n_calc

Should I use Decimal type, BigFloat or something different?

Finally I have to draw plot... (2D Matplotlib plot). Maybe I should "scale" somehow this equation?

Jazzzie
  • 3
  • 4

1 Answers1

0

You could just use this previous answer as reference. OverflowError: (34, 'Result too large') Decimal class has no limit so you should use use. It serves the same purpose as GMP and other arbitrary precision libraries.

I hope this helps you. https://en.wikipedia.org/wiki/List_of_arbitrary-precision_arithmetic_software

ascoder
  • 595
  • 3
  • 14
  • This helps a lot, but at some point I got Decimal Overflow. How to make decimals big enough, even at cost of precision?. And one question more: how to use power properly, should I use pow(), **2 or Context.power() inside equation? – Jazzzie Nov 21 '19 at 12:01
  • On some values of constants, I get **"decimal.Overflow: []"** warning. – Jazzzie Nov 21 '19 at 14:50
  • Now that i see, your program exceeds the maximum float precission which is around 1e308 – ascoder Nov 22 '19 at 19:13
  • I recommend that you scale somehow because it's exponentially increasing. Depends on how you want to deal with the problem. I have found mpmath which documentation i couldn't find because the site is offline but seems very good for this purpose Check this https://stackoverflow.com/questions/11522933/python-floating-point-arbitrary-precision-available – ascoder Nov 22 '19 at 19:22
  • I will try this library (mpmath), docs are working here. Does it cooperate with matplotlib? I need to draw function N(t) for t from 0 to 60. I use matplotlib plots in my application. – Jazzzie Nov 22 '19 at 20:27