简体   繁体   English

有什么方法可以在Python中提取数字的符号吗?

[英]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.

相关问题 有没有办法使用python列表作为原始对象的引用,即使带有“ =”符号? - Is there any way to use python list as reference of original object even with “=” sign? Python - 检查数字是 0 还是 False 的任何方式 - Python - Any way of checking if number 0 or False 是否有任何 python 方法能够提取后面的键值 = 签入长字符串? - Is there any python method that is able to extract value of keys behind = sign in a long string? 是否有任何 python 方法能够在长字符串中提取 [ ] 符号之间的键值? - Is there any python method that is able to extract value of key between [ ] sign in a long string? 有什么方法可以从Python列表中提取并打印原始/文字字符串 - Is there any way to extract and print a raw/literal string from a list in Python 有没有办法用python从网页中提取dataLayer信息? - Is there any way to extract dataLayer information from a webpage with python? Python将数字符号分配给变量 - Python assign sign of number to variable 使用 Python 如何用字符串“abc”替换字符串中以美元符号 ($) 开头的任意数量的子字符串? - Using Python how to replace any number of substrings within a string, starting with dollar sign ($), with a string "abc"? 正则表达式Python提取编号 - Regex Python Extract number 在 python 中搜索字符串中没有正则表达式的 *any* 数字的最快方法? - Fastest way to search for *any* number in string w/o Regex in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM