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

注意,你也可以输入一个浮点数作为参数。