So I am having an issue in my python code that I boiled down to this:
Say we have a function u:
def u(y,t):
h = float(10)
U0 = float(1)
return U0/h*(y)
And an array:
a=np.array([[0]*2]*2)
Then doing the following:
a[1][1] = u(1,0)
But a[1][1] returns 0 despite u(1,0) being equal to 0.1.
Why is this happening and how can I avoid this?
I assume that you actually converted it to a numpy.array before you tried to set the element. So you have something like this somewhere in your code:
import numpy as np
a = np.array(a)
But in that case it's an integer array (because your list of lists contains only integers) and when you try to set an element it will be cast to the type of the array (but: int(0.1) == 0).
You need a float array so you can actually insert floating point values, for example:
a = np.array(a, dtype=float)
Note that you could create that array also with:
a = np.zeros((n, n), dtype=float)
instead of a=[[0]*n]*n (which isn't quite what you expect, see for example "How do I create a 2D list of lists of ints and setting specific values".)
Just to explain this in more detail, assume you have this integer array, all inserted values will be cast to integers:
>>> a = np.array([0, 0, 0])
>>> a[0] = 0.5
>>> a[1] = 1.5
>>> a
array([0, 1, 0])
But if you have a float array you can insert float values:
>>> a = np.array([0, 0, 0], dtype=float)
>>> a[0] = 0.5
>>> a[1] = 1.5
>>> a
array([ 0.5, 1.5, 0. ])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With