marco
marco

Reputation: 187

Numpy: Assignment and evaluation of functions over arrays

I am very new to python. I need to fill a numpy array with values. However I am lost trying to understand the following behaviour:

import numpy as np
bla    = np.array([1,2,3,4])
fTilde = np.full(4,1)

for i in range(4):
    fTilde[i] = bla[i]

print(fTilde)

I obtain the expected

[1,2,3,4]

If I do

import numpy as np
bla    = np.array([1,2,3,4])
bla2   = np.cos(bla)
fTilde = np.full(4,1)

print(bla2)

for i in range(4):
    fTilde[i] = bla2[i]

print(fTilde)

I obtain the surprising result:

[ 0.54030231 -0.41614684 -0.9899925  -0.65364362]
[0 0 0 0]

Finally with

import numpy as np
bla    = np.array([1,2,3,4])
bla2   = np.cos(bla)+1
fTilde = np.full(4,1)

print(bla2)

for i in range(4):
    fTilde[i] = bla2[i]

print(fTilde)

I get the even less expected

[1.54030231 0.58385316 0.0100075  0.34635638]
[1 0 0 0]

I have no idea of what is happening. Any help is welcome.

Upvotes: 0

Views: 90

Answers (1)

Ananda
Ananda

Reputation: 3272

This should fix it.

import numpy as np
bla    = np.array([1,2,3,4])
bla2   = np.cos(bla)
fTilde = np.full(4,1, dtype=np.float32)

print(bla2)

for i in range(4):
    fTilde[i] = bla2[i]

print(fTilde)

The problem is that when you do fTilde = np.full(4,1) the data type that's created is int by default so when you fill it, it's rounded off. Just set the datatype to float and the issue goes away.

Alternatively, you can also just do np.full(4, 1.0) and this also solves the issue.

Upvotes: 2

Related Questions