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.
Answer from DeepSpace on Stack OverflowWhat 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.
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)
Absolute Without abs
Help with absolute value
How to find the absolute value of an integer or float in Python, without using libraries, division, square roots, conditions, or inbuilt functions - Stack Overflow
Calculating absolute value in Python - Stack Overflow
Videos
J, 2 bytes
**
Usage:
f =: **
f 9.3
9.3
f -9.3
9.3
Explanation:
This uses the * verb in both its monadic and dyadic forms. The monadic form returns -1 if it's given a negative number, 0 if it's given 0 and 1 if it's given a positive number. The dyadic form is just plain old multiplication. Putting them in a function literal turns them into a hook which gets evaluated like this: y * (*y).
GolfScript, 4 characters
I believe I win. ;)
Works with integer or decimal numbers of any length.
'-'/
Try it online
These programs do the same and are of equal length:
'-'-
'-'%
GolfScript (old version), 16 13
My first GS program! (that actually does something)
Doesn't work with decimal numbers because GolfScript doesn't have floating point.
~:$0<{0$-}$if
Hello everyone, I am brand new to python and I'm trying to do some exercise but for some reason I cannot solve this one. I need to write a function in which if i is equal or bigger than 0 it returns i as a string and if i is a negative number it returns i as a positive float number.
I've tried this so far:
def int_to_str_flt(i):
if i >= 0 :
return str(i)
else:
return abs(i)
If i is negative it returns a float number but it doesn't make it positive. What's wrong with this? How do I solve that?
{1e999: x, -1e999: -x}[x*1e999]
I'm serious. This works.
The 1e999 is interpreted as a float, but it overflows the available precision, so it's inf. But infinity can be positive or negative. By multiplying x with infinity, we can coerce it into one of two values based on its sign, without using a condition operator. Then we can select x or its negation from a lookup table.
It's equivalent to the following, but doesn't require the import:
from math import inf
{inf: x, -inf: -x}[x*inf]
If you consider the built-in classes (int, str, etc) to be built-in "functions". You could do something like the following
num.__class__(('%s' % num).lstrip('-'))
Convert the number to a string, strip the negative sign and then use the original numbers class to convert back
You can do it with the built-in abs() function:
absolute_val = abs(x)
Otherwise, without the built-in function, use math:
absolute_val = (x ** 2) ** 0.5
You wanted to calculate the absolute value using python. Here Im providing the code:
Python code function: abs(Number)
Python code example: abs(-100)
Python code example: abs(105-20)
Python code example: abs(100-200)
Output:

The problem is with the loop you are using , Trying modifying it this way
def abs1(array):
for i in range(len(array)):
if array[i] < 0:
array[i] = array[i] * (-1)
print(array)
The reason is the loop you were previously using was just for accesing list elements but not giving you reference to change anything in list I solved it with using indexes on list.
Try :
import numpy as np
array= ...
np.abs(np.array(array))
numpy is very powerful and fast, learn to use it asap.
EDIT since the problem is how to do a function on each element of a list and wrap those results in a list of the same length :
Two solutions come to mind :
- hardcore python style :
[x if x<0 else -x for x in array]
the brackets say I want a list, inside I write the function and I say where to find the parameters to my function.
[abs(x) for x in array]
[f(x) for x in array] # for any defined f that can handle every element of array
- map(lambda x : f(x), array)
you create a mapping on the elements of array. To those elements, you apply lambda. lambda is a way to define a function locally, very locally.
list(map(lambda x : abs(x),array))
finally you make a list from the mapping, to retrieve the result. If you don't, it will stay as an abstract, the definition of a relation between array and something that is yet to be instantiated.
We have a little project where we are supposed to program absolute value without math.abs method. The question goes like this: "Suppose x and y are variables of type double. Write a program that reads in x and then sets y to the absolute value of x without calling the Math.abs() method."
Can someone help me with the code? What do you even code to accomplish this? Thank you in advance!!
I think you can probably figure this one out just with a hint.
What happens to negative numbers when they are multiplied by -1?
Note that you can check if numbers are less than zero using if and then do something about less than zero numbers.
If you still get stuck after thinking on that for a few minutes shoot me a pm.
Edit: as long as you don't ask me to just write out all the code for you.
You could just see if the number is less than 0 and then multiply it by -1
You don't need to import add() for this.
Why don't you simply do
def a_plus_absolute_b(a, b):
"""Return a+abs(b), but without calling abs."""
if b < 0:
result = a - b
else:
result = a + b
return result
The solution you're looking for, which you're overlooking because you're obsessed with the idea of "negative", is as follows:
from operator import add, sub
def a_plus_absolute_b(a, b):
"""Return a+abs(b), but without calling abs."""
if b < 0:
op = sub
else:
op = add
return op(a, b)
Note how the parens, used to call a function, are only in the last line.
Hello,
I am not very familiar with python, my script is referencing an index of a notepad document. For example:
Value = lines[firsttag][9:21]
In this case, it is referencing a number in the notepad document which contains 12 characters. And I need the absolute value of it. Every time I put the โabs()โ after the equal sign or even after the [firsttag]. My code errors out. Please advise.
It's likely because there a built-in functions with the same name, abs. The same is true for np.amax, np.amin and np.round_.
The aliases for the NumPy functions abs, min, max and round are only defined in the top-level package.
So np.abs and np.absolute are completely identical. It doesn't matter which one you use.
There are several advantages to the short names: They are shorter and they are known to Python programmers because the names are identical to the built-in Python functions. So end-users have it easier (less to type, less to remember).
But there are reasons to have different names too: NumPy (or more generally 3rd party packages) sometimes need the Python functions abs, min, etc. So inside the package they define functions with a different name so you can still access the Python functions - and just in the top-level of the package you expose the "shortcuts". Note: Different names are not the only available option in that case: One could work around that with the Python module builtins to access the built-in functions if one shadowed a built-in name.
It might also be the case (but that's pure speculation on my part) that they originally only included the long-named functions absolute (and so on) and only added the short aliases later. Being a large and well-used library the NumPy developers don't remove or deprecate stuff lightly. So they may just keep the long names around because it could break old code/scripts if they would remove them.
There also is Python's built-in abs(), but really all those functions are doing the same thing. They're even exactly equally fast! (This is not the case for other functions, like max().)

Code to reproduce the plot:
import numpy as np
import perfplot
def np_absolute(x):
return np.absolute(x)
def np_abs(x):
return np.abs(x)
def builtin_abs(x):
return abs(x)
b = perfplot.bench(
setup=np.random.rand,
kernels=[np_abs, np_absolute, builtin_abs],
n_range=[2 ** k for k in range(25)],
xlabel="len(data)",
)
b.save("out.png")
b.show()