Функция знака числа питон

Sign function in Python (sign/signum/sgn, copysign)

In Python, the built-in functions and standard libraries do not provide the sign function, i.e., the function that returns 1 , -1 , or 0 depending on the sign of the number. If you need such a function, you could use numpy.sign() from NumPy or define your own function.

The sign function (sign, signum, sgn)

The sign function returns 1 for positive numbers, -1 for negative numbers, and 0 for zero.

As mentioned in the introduction, as of version 3.11, Python does not include the sign function in its built-in functions or standard libraries.

See Stack Overflow and Python Bug Tracker below for reasons why the sign function is not provided in Python.

They decided to implement copysign() instead of sign() so that users can decide what value should be returned in edge cases such as +0.0 , -0.0 , NaN , and -NaN .

For more information on signed zero, see below.

In Python, the floating-point data type float can represent a negative zero, denoted as -0.0 .

There is no distinction between positive and negative zeros in the integer int ; -0 is interpreted as 0 .

print(0) # 0 print(-0) # 0 print(0 == -0) # True print(0 is -0) # True 

In contrast, float treats 0.0 and -0.0 as equivalent, yet distinct objects.

print(0.0) # 0.0 print(-0.0) # -0.0 print(0.0 == -0.0) # True print(0.0 is -0.0) # False 

numpy.sign()

NumPy provides numpy.sign() . If a sign function is required, numpy.sign() is a convenient choice when NumPy is accessible.

numpy.sign() returns int for int inputs and float for float inputs.

import numpy as np print(np.sign(100)) # 1 print(np.sign(-100)) # -1 print(type(np.sign(100))) # print(np.sign(1.23)) # 1.0 print(np.sign(-1.23)) # -1.0 print(type(np.sign(1.23))) # 

It returns zero for all zeros, including the negative zero -0.0 .

print(np.sign(0)) # 0 print(np.sign(0.0)) # 0.0 print(np.sign(-0.0)) # 0.0 
print(np.sign(float('nan'))) # nan print(np.sign(float('-nan'))) # nan 

numpy.sign() works with both scalar values and NumPy arrays ( ndarray ). Refer to the following article for more details.

Examples of implementation of sign()

With comparison operators

In Python, comparison operations typically return True and False . Since bool is a subclass of int , True can be treated as 1 and False as 0 .

print(100 > 0) # True print(True - False) # 1 print(False - True) # -1 print(False - False) # 0 

Based on this, you can define the sign function as follows:

def my_sign(x): return (x > 0) - (x  0) 

The result is always an integer int .

print(my_sign(100)) # 1 print(my_sign(-100)) # -1 print(type(my_sign(100))) # print(my_sign(1.23)) # 1 print(my_sign(-1.23)) # -1 print(type(my_sign(-1.23))) # 

Both zero and NaN consistently return 0 , regardless of their signs.

print(my_sign(0)) # 0 print(my_sign(0.0)) # 0 print(my_sign(-0.0)) # 0 print(my_sign(float('nan'))) # 0 print(my_sign(float('-nan'))) # 0 

This function does not support complex numbers.

# print(my_sign(3 + 4j)) # TypeError: '>' not supported between instances of 'complex' and 'int' 

Note that some implementations of special methods such as __lt__ may return values other than True or False .

By convention, False and True are returned for a successful comparison. However, these methods can return any value, so if the comparison operator is used in a Boolean context (e.g., in the condition of an if statement), Python will call bool() on the value to determine if the result is true or false. 3. Data model — __lt__ — Python 3.11.3 documentation

When using built-in types like int and float , you don’t need to worry about this, but caution is required when dealing with user-defined classes.

With abs()

You can also define the sign function using the built-in function abs() , which returns the absolute value of a number.

Here, the conditional expression is employed.

def my_sign_with_abs(x): return 0.0 if abs(x) == 0 else x / abs(x) 

This example returns a floating-point number float because it uses division / to support complex numbers, as described below.

print(my_sign_with_abs(100)) # 1.0 print(my_sign_with_abs(-100)) # -1.0 print(type(my_sign_with_abs(100))) # print(my_sign_with_abs(1.23)) # 1.0 print(my_sign_with_abs(-1.23)) # -1.0 print(type(my_sign_with_abs(1.23))) # 

It returns 0.0 for zero and NaN for NaN .

print(my_sign_with_abs(0)) # 0.0 print(my_sign_with_abs(0.0)) # 0.0 print(my_sign_with_abs(-0.0)) # 0.0 print(my_sign_with_abs(float('nan'))) # nan print(my_sign_with_abs(float('-nan'))) # nan 

Since abs() returns absolute values (distances on the complex plane) for complex numbers as well, this implementation also supports complex numbers.

print(abs(3 + 4j)) # 5.0 print(my_sign_with_abs(3 + 4j)) # (0.6+0.8j) 

It returns a unit vector pointing in the same direction as the original complex number.

The signum of a given complex number z is the point on the unit circle of the complex plane that is nearest to z. Sign function — Complex signum — Wikipedia

math.copysign()

While Python does not provide a sign() function, it does include the copysign() function in its math module.

math.copysign() returns a float with the absolute value of its first argument and the sign of its second argument.

import math print(math.copysign(123, -100)) # -123.0 print(math.copysign(123.0, -100.0)) # -123.0 

You can define the function like the sign function using math.copysign() . Note that its behavior differs from the typical sign() function as it doesn’t return 0 for 0 as described below.

def my_sign_with_copysign(x): return int(math.copysign(1, x)) 

This example uses int() to always return an int .

print(my_sign_with_copysign(100)) # 1 print(my_sign_with_copysign(-100)) # -1 print(type(my_sign_with_copysign(100))) # print(my_sign_with_copysign(1.23)) # 1 print(my_sign_with_copysign(-1.23)) # -1 print(type(my_sign_with_copysign(1.23))) # 

It returns 1 for an integer zero, and 1 or -1 for a floating-point zero, depending on its sign.

print(my_sign_with_copysign(0)) # 1 print(my_sign_with_copysign(0.0)) # 1 print(my_sign_with_copysign(-0.0)) # -1 

It returns 1 or -1 for NaN as well, depending on its sign.

print(my_sign_with_copysign(float('nan'))) # 1 print(my_sign_with_copysign(float('-nan'))) # -1 

Since math.copysign() does not support complex numbers, this function does not support complex numbers either.

# print(math.copysign(1, 3 + 4j)) # TypeError: can't convert complex to float # print(my_sign_with_copysign(3 + 4j)) # TypeError: can't convert complex to float 

Источник

Sign Function in Python – Get Sign of Number

In Python, there is no sign function, but it is easy to get the sign of a number by defining our own sign function.

def sign_function(x): if x > 0: return 1 elif x == 0: return 0 else: return -1 print(sign_function(-10)) # Output: -1

You can also use the Math module copysign() function – the second parameter is the number which you want to check the sign.

print(math.copysign(1, -3)) # Output: -1

The numpy module also has a sign function you can use to get the sign of numbers in an array.

import numpy as np print(np.sign([10,0,-10]) # Output: [1, 0, -1]

In mathematics and computer science, the sign function is simple yet very common and useful for many applications.

By definition, the sign function is a function where numbers greater than 0 are assigned a value of 1, numbers equal to 0 are assigned a value of 0, and numbers less than 1 are assigned a value of -1.

When working in Python, it may be useful to be able to easily find the sign of numbers.

Unfortunately, there is not a built-in sign function, but we can easily define one ourselves.

Below is an example of how you can create your own sign function in Python.

def sign_function(x): if x > 0: return 1 elif x == 0: return 0 else: return -1 print(sign_function(10)) print(sign_function(-10)) # Output: 1 -1

How to Find the Sign of a Number in Python with the Math Module

If you don’t want to define your own sign function, you can use a function from the math module.

While the math module doesn’t have a sign function, the copysign() function from the math module can return the sign of a number.

The copysign() function takes two inputs. The idea with copysign() is it returns the first input with the sign of the second input.

So if all you want is the sign of a number, you can pass ‘1’ for the first input and your number for the second input.

Below is a simple example showing how to use the math module copysign() function in Python.

print(math.copysign(1, -3)) print(math.copysign(1, 5)) # Output: -1 1

Using the numpy Module Sign Function to Find the Signs of Numbers in an Array

The numpy module also has a sign function.

You can use the numpy module sign function to find the sign of numbers in an array. Just pass an array of numbers and you will get back an array of their signs.

Below is an example of how you can find the signs of numbers in an array in Python with numpy.

import numpy as np print(np.sign([10,0,-10]) # Output: [1, 0, -1]

Hopefully this article has been useful for you to learn how to create a Python sign function and find the sign of numbers in Python.

  • 1. Using Python to Return Two Values from Function
  • 2. Clear File Contents with Python
  • 3. pandas floor – Find the Floor of a Column Using Numpy floor
  • 4. How to Group By Columns and Find Maximum in pandas DataFrame
  • 5. Pascal’s Triangle in Python
  • 6. Convert String to Float with float() in Python
  • 7. pandas set_value – Using at() Function to Set a Value in DataFrame
  • 8. How to Count Vowels in a String Using Python
  • 9. Using Python to Read File Word by Word
  • 10. Using Python to Remove First Character from String

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Источник

Читайте также:  Python exec permission denied
Оцените статью