how to get absolute value without 'abs' function?

时光毁灭记忆、已成空白 提交于 2020-05-01 09:02:34

问题


def my_abs(value):
"""Returns absolute value without using abs function"""
    if value < 5 :
        print(value * 1)
    else:
        print(value * -1)
print(my_abs(3.5))

that's my code so far but the quiz prints, for example -11.255 and 200.01 and wants the opposite for example it wants 11.255 back and -200.01


回答1:


What does 5 have to do with absolute value?

Following your logic:

def my_abs(value):
    """Returns absolute value without using abs function"""
    if value <= 0:
        return value * -1
    return value * 1

print(my_abs(-3.5))
>> 3.5
print(my_abs(3.5))
>> 3.5

Other, shorter solutions also exist and can be seen in the other answers.




回答2:


A simple solution for rational numbers would be

def my_abs(value):
    if value<0:
        return -value
    return value



回答3:


Why do you want to check if value < 5?

Anyways, to replicate the abs function:

def my_abs(value):
    return value if value >=0 else -1 * value 



回答4:


The solutions so far don't take into account signed zeros. In all of them, an input of either 0.0 or -0.0 will result in -0.0.

Here is a simple and (as far as I see) correct solution:

def my_abs(value):
    return (value**2)**(0.5)


来源:https://stackoverflow.com/questions/38587114/how-to-get-absolute-value-without-abs-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!