[Tutor] numerical problem

Andre Engels andreengels at gmail.com
Thu Oct 15 12:59:57 CEST 2009

On Thu, Oct 15, 2009 at 11:28 AM, Mr Timothy Hall
<timothy.hall at uqconnect.edu.au> wrote:
>  hi,
> i am writing a program for a runge-cutter method of solving ODE's and im
> having a problem with one part.
> whenever i run this part of the program, no matter what values i put in for
> vto, k1t etc... it always equals zero.
> im slightly aware of floating point numbers but im not sure why this will
> not give me a real answer.
> when i do it on my calculator the answer is 0.897 for the correct values of
> k3t etc. so its not like the result
> is extremely small.
> any help would be great.
> def runge_tang(vto,k1t,k3t,k4t,k5t,k6t):
>     vn = vto+(16/135)*k1t+(6656/12825)*k3t+(28561/56430)*k4t-(9/50)*k5t+(2/55)*k6t
>     return vn

The problem is that Python 2 (it has changed in Python 3) uses integer
division when making the quotient of integers. 16/135 is thus
evaluated to zero, 6656/12825 as well, etcetera.

There are 2 ways to solve this:
1. At the top of your file, add the line "from __future__ import
division" - this makes the division behave as in Python 3, which uses
floating point division when dividing integers as well.
2. Change something to float before doing the division, for example through:

vn = vto+(float(16)/135)*k1t+(float(6656)/12825)*k3t+(float(28561)/56430)*k4t-(float(9)/50)*k5t+(float(2)/55)*k6t


vn = vto+(16.0/135)*k1t+(6656.0/12825)*k3t+(28561.0/56430)*k4t-(9.0/50)*k5t+(2.0/55)*k6t

André Engels, andreengels at gmail.com

More information about the Tutor mailing list