Why is python calculating this way?

77 Views Asked by At

I tried to print a values from a 2-dimensions-array in python's numpy:

print(y[-1,-1], 1-y[-1,-1], -y[-1,-1], 1+y[-1,-1])

and here is what I got printed:

0.498714091773 0.501285908227 -0.498714091773 1.49871409177

Why is the value of y[-1,-1] 0.498714091773 and the one of 1-y[-1,-1] 0.501285908227? If we take the limits of the ability of my computer in consideration, wouldn't 1-y[-1,-1] be something like 0.499 and something?

Here is how I define my code and where y[] comes from:

def mouse(t, y):
    dy = np.array([1-(y[0]+y[1]), y[0]-y[1]])
    return dy

def euler(f, x, y, h):
    yn = y + h*f(x,y)
    xn = x + h
    return xn, yn

def integrate(method, f, t0, y0, tend, h):
    T = [t0]
    Y = [y0]
    t = t0
    y = y0
    while t < tend:
        h = min(h, tend-t)
        t, y = method(f, t, y, h)
        T.append(t)
        Y.append(y)
    return np.array(T), np.array(Y)

t, y = integrate(euler, mouse, 0, [0,0], 6, 0.05)
print(y[-1,-1], 1-y[-1,-1], -y[-1,-1], 1+y[-1,-1])
1

There are 1 best solutions below

4
On

I didn't chase through your code to see where $y[-1,-1]$ comes from. It looks like it is a numerical integration that might have an analytic value of $\frac 12$. Given the value for $y[-1,-1]$ the other values are exactly what you would expect. If you add $y[-1,-1]$ to $1-y[-1,-1]$ you get $1$ very nicely. Why should $1-y[-1,-1]$ be $0.499$ You are doing exactly the same computation of $y[-1,-1]$ each time, so it should return the same value, then you are negating it, subtracting from $1$, and adding to $1$