Yay
Yay

Reputation: 45

Dividing a part of numpy array by a constant

I am having trouble understanding what happens when I divide a part of a numpy array by a constant. If I run

import numpy as np

a = np.array([1,2,3])
a[:2] = a[:2]/2
print(a)

I get

[0 1 3]

Why doesn't a equal array([0.5, 1.0, 3]), and how do I get a to equal that?

Upvotes: 0

Views: 4774

Answers (1)

marcel h
marcel h

Reputation: 788

As suggested by the comments while writing this example. However, it is written, so here it goes:

By creating the array and passing only ints the array is of type dtype('int64') (from the first print). You can set it explicitly to float as shown for the second example, which delivers your expected output.


import numpy as np

a = np.array([1,2,3])
a[:2] = a[:2]/2
print(a)

a.dtype


b = np.array([1,2,3], dtype=np.float16)
b[:2] = b[:2]/2
print(b)

b.dtype

Upvotes: 1

Related Questions