Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Difference between + and np.add()

I have this code:

import numpy as np


a = np.arange(10)

b = a + 1
c = np.add(a, 1)

print("a:", a)
print("b:", b)
print("c:", c)

Which prints:

a: [0 1 2 3 4 5 6 7 8 9]
b: [ 1  2  3  4  5  6  7  8  9 10]
c: [ 1  2  3  4  5  6  7  8  9 10]

I want to know what is the difference between a + 1 and np.add(a, 1)?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

numpy.add is the NumPy addition ufunc. Addition operations on arrays will usually delegate to numpy.add, but operations that don’t involve arrays will usually not involve numpy.add.

For example, if we have two ordinary ints:

In [1]: import numpy

In [2]: numpy.add(1, 2)
Out[2]: 3

In [3]: type(_)
Out[3]: numpy.int64

In [4]: 1 + 2
Out[4]: 3

In [5]: type(_)
Out[5]: int

numpy.add will coerce the inputs to NumPy types, perform NumPy addition logic, and produce a NumPy output, while + performs ordinary Python int addition and produces an ordinary int.

Aside from that, numpy.add has a lot of additional arguments to control and customize how the operation is performed. You can specify an out array to write the output into, or a dtype argument to control the output dtype, or many other arguments for advanced use cases.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading