---
title: subtract
description: "将输入参数逐元素相减。"
url: https://www.hikunpeng.com/document/detail/zh/kunpenghpcs/hpckit/devg/kunpengaccel_kml_1086.html
sourcePath: /source/zh/kunpenghpcs/hpckit/devg/kunpengaccel_kml_1086.html
indexId: ba3aa3531386cfa0cd58ce946bf652f85039de628118d0a03add06c20d4d3e3e61
---
# subtract

#### 功能描述

将输入参数逐元素相减。


#### 必选输入参数

| 参数名 | 类型 | 说明 |
| --- | --- | --- |
| x1，x2 | array\_like | 相减的数组或标量，如果x1.shape!=x2.shape，则它们必须能广播至相同的形状。 |


#### 可选输入参数

| 参数名 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| out | ndarray或ndarray的元组 | None | 计算结果保存的位置。如果提供，其形状必须与输入数组广播后的形状一致。未指定时，返回一个新的数组。 |
| where | array\_like | None | 将被广播至输入的条件数组。在条件为真处的元素，其计算结果会存入out中，其余位置保留原有值。 |
| \*\*kwargs | \- | \- | 其他关键字参数，请参见NumPy官方文档Universal functions (ufunc)(https://numpy.org/doc/stable/reference/ufuncs.html\#ufuncs\-kwargs)。 |


#### 返回数据

| 类型 | 说明 |
| --- | --- |
| ndarray/scalar | x1和x2逐元素相减的结果。 |


#### 示例

```
>>> import numpy as np
>>> np.subtract(1.1, 5.5)
-4.4
>>> x1 = np.arange(9.0).reshape((3,3))
>>> x2 = np.arange(3.0)
>>> x1
array([[0., 1., 2.],
       [3., 4., 5.],
       [6., 7., 8.]])
>>> x2
array([0., 1., 2.])
>>> 
>>> np.subtract(x1, x2)
array([[ 0.,  0.,  0.],
       [ 3.,  3.,  3.],
       [ 6.,  6.,  6.]])
>>

#  若x1和x2均为ndarray，那么还可以使用“-”来替代np.subtract

>>> x1 = np.arange(0, 4).reshape((2,2))
>>> x1
array([[0, 1],
       [2, 3]])
>>> x2 = np.arange(4, 8).reshape((2,2))
>>> x2
array([[4, 5],
       [6, 7]])
>>> 
>>> x1 - x2
array([[ -4,  -4],
       [ -4,  -4]])
>>>
```
