Home > front end >  Dividing a part of numpy array by a constant
Dividing a part of numpy array by a constant

Time:10-05

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?

CodePudding user response:

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

  • Related