有没有办法在Python中提取数字的符号?

2024-05-16 22:48:03 发布

您现在位置:Python中文网/ 问答频道 /正文

Python中的zanam编码算法。这是我目前的代码:

def Bolzano(fonction, a, b, tol=0.000001):
   while abs(b-a)>tol:
       m=(a+b)/2
       if cmp(fonction(m))==cmp(fonction(a)):
           a=m
       else:
           b=m
   return a, b

它一直工作,直到遇到它无法识别的cmp。但是,我没有看到其他方法可以做到这一点,因为Python没有符号函数。有没有其他方法提取数字的符号?你知道吗


Tags: 方法代码算法编码ifdef符号abs
3条回答
def same_sign(a, b):
    return (a * b) >= 0

示例:

>>> same_sign(3, 4)
True

>>> same_sign(-3, 4)
False

>>> same_sign(3, -4)
False

>>> same_sign(-3, -4)
True

>>> same_sign(-3, 0)
True

可能使用:

if cmp(fonction(m),fonction(a)) == 0:

Is there any other way to extract the sign of a number?

写你自己的怎么样?你知道吗

实施

def sign(num):
    return -1 if num < 0 else 1

示例

>>> sign(10)
1
>>> sign(-10)
-1

Ohh和cmp是一个内置的,它需要两个参数(数字),只需比较它们并检查哪个更大。你应该这样使用它

def Bolzano(fonction, a, b, tol=0.000001):
   while abs(b-a)>tol:
       m=(a+b)/2
       if cmp(fonction(m), fonction(a)) == 0:
           a=m
       else:
           b=m
   return a, b

相关问题 更多 >