Home > Mobile >  How to raise all values to the power of 2, but keep their original sign
How to raise all values to the power of 2, but keep their original sign

Time:07-06

How do I raise all values for the vector v = [4,7,-2,9,3,-6,-4,1]to the power of 2, but keep their original sign ?

CodePudding user response:

>>> from math import copysign
>>> v = [4,7,-2,9,3,-6,-4,1]
>>> [int(copysign(x*x,x)) for x in v]
[16, 49, -4, 81, 9, -36, -16, 1]

The copysign function basically does what you want: Return the first argument, but with the sign of the second. Except that copysign always returns a float, so if you want ints, you cast them back. (Beware of overflow!)

CodePudding user response:

I like @Sören's method better, but if you prefer not to have to import math for some reason, this will work.

>>> v = [4,7,-2,9,3,-6,-4,1]
>>> result = [x*abs(x) for x in v]
>>> print(result)
[16, 49, -4, 81, 9, -36, -16, 1]

We do x * abs(x) and to keep the sign. If the original number is positive, both x and abs(x) will be positive, yielding a positive answer. If the original is negative, x will retain the original sign, meaning we get a negative.

I use a list comprehension, and then wrap it in int(...) to make it an int again (from a float).

  • Related