Python > Core Python Basics > Fundamental Data Types > Floating-point numbers (float)

Float Type Conversion and Special Values

This snippet demonstrates how to convert other data types to floats and discusses special float values like infinity and NaN (Not a Number).

Converting to Float

The `float()` function converts integers and strings to floating-point numbers. Strings must represent valid numerical values (with a decimal point, if applicable) to be converted successfully.

# Converting integers and strings to float
integer_value = 10
string_value = "3.14"

float_from_integer = float(integer_value)
float_from_string = float(string_value)

# Printing the results
print(f"Float from integer: {float_from_integer}, type: {type(float_from_integer)}")
print(f"Float from string: {float_from_string}, type: {type(float_from_string)}")

Special Float Values: Infinity and NaN

Python supports special float values: positive infinity (`float('inf')`), negative infinity (`float('-inf')`), and NaN (`float('nan')`). NaN represents an undefined or unrepresentable value, often resulting from invalid mathematical operations (e.g., dividing zero by zero or taking the square root of a negative number). Any arithmetic operation involving NaN will result in NaN.

import math

# Representing infinity
positive_infinity = float('inf')
negative_infinity = float('-inf')

# Representing NaN (Not a Number)
not_a_number = float('nan')
not_a_number_math = math.nan

# Printing the special values
print(f"Positive Infinity: {positive_infinity}")
print(f"Negative Infinity: {negative_infinity}")
print(f"NaN (Not a Number): {not_a_number}")
print(f"NaN (Not a Number) using math: {not_a_number_math}")

#Demonstrating NaN propagation
result_nan = not_a_number + 5
print(f"NaN + 5: {result_nan}")

Using Infinity and NaN in Calculations

Division by zero results in infinity (positive or negative depending on the sign of the numerator). Attempting to calculate the square root of a negative number results in NaN. The `math.isnan()` function can be used to check if a float value is NaN.

import math

# Dividing by zero results in infinity
result_infinity = 1.0 / 0.0
print(f"1.0 / 0.0: {result_infinity}")

# Square root of a negative number results in NaN
result_nan = math.sqrt(-1.0)
print(f"Square root of -1.0: {result_nan}")

#Checking for NaN Values:
print(f"Is result_nan a NaN value? {math.isnan(result_nan)}")

Real-Life Use Case: Handling Missing Data

NaN values are commonly used to represent missing or undefined data in datasets. They allow for calculations to proceed without crashing when encountering missing values, although the result may also be NaN. Infinity can be useful to represent unbounded quantities.

Best Practices

  • Always validate input data when converting to floats to avoid errors.
  • Use math.isnan() to check for NaN values explicitly before performing operations that might be affected by them.
  • Handle infinity and NaN values appropriately in your application logic to prevent unexpected behavior.

Interview Tip

Be prepared to explain the concepts of infinity and NaN and how they arise in floating-point arithmetic. Also, know how to detect and handle these values in Python.

When to Use Type Conversion to Float

Use type conversion to float when you need to ensure that a variable is represented as a floating-point number, especially when performing calculations that require decimal precision or when dealing with data from external sources (e.g., files or user input).

Memory Footprint

Converting an integer or string to a float doesn't significantly change the memory footprint if the integer could also have been represented as a float. The float will still occupy 8 bytes.

Alternatives

There are no direct alternatives to float conversion if you need a floating point representation. However, you can use exception handling (try-except blocks) to manage potential `ValueError` exceptions that might occur during string conversion.

Pros

  • Enables calculations involving integers and strings with floating-point numbers.
  • Provides a way to represent missing data with NaN.
  • Allows for handling unbounded quantities with infinity.

Cons

  • Conversion from strings can raise ValueError if the string doesn't represent a valid number.
  • Arithmetic operations with NaN propagate the NaN value.
  • Division by zero can lead to infinity, which might not be desirable in all situations.

FAQ

  • What happens if I try to convert a non-numeric string to a float?

    Attempting to convert a non-numeric string (e.g., "hello") to a float will raise a `ValueError` exception. You should use error handling (try-except blocks) to gracefully handle such situations.
  • How can I check if a value is finite (not infinite or NaN)?

    You can use the `math.isfinite()` function to check if a float value is finite (i.e., not infinite or NaN). This function returns `True` if the value is finite and `False` otherwise.