megengine.functional.add#

add(x, y)[source]#

Element-wise addition.

Calculates the sum for each element \(x_i\) of the input tensor \(x\) with the respective element \(y_i\) of the input tensor \(y\).

Parameters:
Return type:

Tensor

Returns:

A tensor containing the element-wise sums. The returned tensor must have a data type determined by Type promotion rules.

Special cases

For floating-point operands,

  • If either \(x\) or \(y\) is NaN, the result is NaN.

  • If \(x\) is +infinity and \(y\) is -infinity, the result is NaN.

  • If \(x\) is -infinity and \(y\) is +infinity, the result is NaN.

  • If \(x\) is +infinity and \(y\) is +infinity, the result is +infinity.

  • If \(x\) is -infinity and \(y\) is -infinity, the result is -infinity.

  • If \(x\) is +infinity and \(y\) is a finite number, the result is +infinity.

  • If \(x\) is -infinity and \(y\) is a finite number, the result is -infinity.

  • If \(x\) is a finite number and \(y\) is +infinity, the result is +infinity.

  • If \(x\) is a finite number and \(y\) is -infinity, the result is -infinity.

  • If \(x\) is -0 and \(y\) is -0, the result is -0.

  • If \(x\) is -0 and \(y\) is +0, the result is +0.

  • If \(x\) is +0 and \(y\) is -0, the result is +0.

  • If \(x\) is +0 and \(y\) is +0, the result is +0.

  • If \(x\) is either +0 or -0 and \(y\) is a nonzero finite number, the result is \(y\).

  • If \(x\) is a nonzero finite number and \(y\) is either +0 or -0, the result is \(x\).

  • If \(x\) is a nonzero finite number and \(y\) is \(-x\), the result is +0.

  • In the remaining cases, when neither infinity, +0, -0, nor a NaN is involved, and the operands have the same mathematical sign or have different magnitudes, the sum must be computed and rounded to the nearest representable value according to IEEE 754-2019 and a supported round mode. If the magnitude is too large to represent, the operation overflows and the result is an infinity of appropriate mathematical sign.

Note

  • Floating-point addition is a commutative operation, but not always associative.

  • The + operator can be used as a shorthand for add on tensors.

Examples

>>> F.add(1.0, 4.0)
Tensor(5.0, device=xpux:0)

Element-wise addition:

>>> x = Tensor([[1, 2, 3], [4, 5, 6]])
>>> y = Tensor([[1, 1, 1], [2, 2, 2]])
>>> F.add(x, y)
Tensor([[2 3 4]
 [6 7 8]], dtype=int32, device=xpux:0)

Broadcasting:

>>> x = Tensor([[1, 2, 3], [4, 5, 6]])
>>> F.add(x, 1)
Tensor([[2 3 4]
 [5 6 7]], dtype=int32, device=xpux:0)