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)?
>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.