Python math.copysign()方法
Pythonmath.copysign()
方法是一种有效的方法,可以从参数x
中找到幅度,从参数y
中找到符号 (+
或-
) 。
语法
math.copysign(x,y)
参数
x |
任何整数值。 |
y |
任何我们需要符号的整数值。 |
返回值
此方法的返回类型是一个float
,代表新的数值,由x
的大小和y
的符号组成。
例子
使用Pythonmath.copysign()
方法而不使用函数
代码摘录:
import math
x=7
y=-6
value=math.copysign(x,y)
print(f"The magnitude of {x} & sign of {y} returns the value of {value}.")
x=-8
y=-6
value=math.copysign(x,y)
print(f"The magnitude of {x} & sign of {y} returns the value of {value}.")
x=-9
y=1
value=math.copysign(x,y)
print(f"The magnitude of {x} & sign of {y} returns the value of {value}.")
输出:
The magnitude of 7 & sign of -6 returns the value of -7.0.
The magnitude of -8 & sign of -6 returns the value of -8.0.
The magnitude of -9 & sign of 1 returns the value of 9.0.
absolute value
为了更好地理解,假设返回的值的大小是a
,但符号是b
。
使用Pythonmath.copysign()
方法和函数
代码摘录:
import math
def func(x, y):
value = math.copysign(x, y)
return value
print (func(10, -10))
输出:
-10.0
注意,你也可以输入一个浮点数作为参数。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。