[英]Any way to extract the sign of a number in Python?
I have am coding the algorithm of Bolzano in Python. 我正在用Python编码Bolzano的算法。 This is my code for now:
这是我现在的代码:
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
It works until it encounters cmp, which it doesn't recognise. 它会一直工作到遇到无法识别的cmp。 However I don't see another way to do it, since Python doesn't have a sign function.
但是我没有看到另一种方法,因为Python没有符号函数。 Is there any other way to extract the sign of a number?
还有其他方法可以提取数字的符号吗?
Is there any other way to extract the sign of a number?
还有其他方法可以提取数字的符号吗?
How about writing your own? 自己写吧?
Implementation 实作
def sign(num):
return -1 if num < 0 else 1
Example 例
>>> sign(10)
1
>>> sign(-10)
-1
Ohh and cmp is a built-in that requires two parameters (numbers) and simply compares them and checks which of them is larger. Ohh和cmp是内置的,它需要两个参数(数字),只需将它们进行比较并检查其中哪个较大。 You should have used it as follows
您应该按如下方式使用它
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
可能使用:
if cmp(fonction(m),fonction(a)) == 0:
def same_sign(a, b):
return (a * b) >= 0
Examples: 例子:
>>> 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.