7

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?

2
  • 1
    try a[1][1] = u(1.0,0.0) Commented Jun 12, 2017 at 13:36
  • btw a=[[0]*n]*n is very wrong. do a = [[0]*n] for _ in range(n)] instead or all row references are identical. Commented Jun 12, 2017 at 13:37

1 Answer 1

14

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. ])
Sign up to request clarification or add additional context in comments.

1 Comment

XD. Literally the dumbest feature I've ever seen. dtype should be a required parameter. Way too dangerous to allow this thing

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.