[Numpy-discussion] Integer cast problems
Ryan May
rmay31@gmail....
Thu Feb 12 11:35:05 CST 2009
On Thu, Feb 12, 2009 at 11:21 AM, Ralph Kube <ralphkube@googlemail.com>wrote:
> Hi there,
> I have a little problem here with array indexing, hope you see the problem.
> I use the following loop to calculate some integrals
>
> import numpy as N
> from scipy.integrate import quad
> T = 1
> dt = 0.005
> L = 3
> n = 2
> ints = N.zeros([T/dt])
>
> for t in N.arange(0, T, dt):
> a = quad(lambda
> x:-1*(1-4*(t**4))*N.exp(-t**4)*N.exp(-x**2)*N.cos(n*N.pi*(x-L)/(2*L)),
> -L, L)[0]
> ints[int(t/dt)] = a
> print t, N.int32(t/dt), t/dt, a, ints[int(t/dt)]
>
> The output from the print statement looks like:
>
> 0.14 28 28.0 2.52124867251e-16 2.52124867251e-16
> 0.145 28 29.0 2.03015199575e-16 2.03015199575e-16
> 0.15 30 30.0 2.40857836418e-16 2.40857836418e-16
> 0.155 31 31.0 2.52191011339e-16 2.52191011339e-16
>
> The same happens on the ipython prompt:
>
> 0.145 * 0.005 = 28.999999999999996
> N.int32(0.145 * 0.005) = 28
>
> Any ideas how to deal with this?
>
I'm assuming you mean 0.145 / 0.005 = 28.999999999999996
When you cast to an integer, it *truncates* the fractional part, and life
with floating point says that what should be an exact result won't
necessarily be exact. Try using N.around.
Ryan
--
Ryan May
Graduate Research Assistant
School of Meteorology
University of Oklahoma
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://projects.scipy.org/pipermail/numpy-discussion/attachments/20090212/f1a96c3d/attachment.html
More information about the Numpy-discussion
mailing list