In Python, the float
data type is used to represent decimal numbers or numbers with a fractional component.
Here are some examples of floats:
3.14
-0.001
2.71828
0.0
You can perform various operations on floats, just like with integers.
For example:
a = 3.14
b = 2.71
# Addition
sum_result = a + b # result will be 5.85
# Subtraction
difference = a - b # result will be 0.43
# Multiplication
product = a * b # result will be 8.5094
# Division
quotient = a / b # result will be 1.1589850746...
Floats can also represent very large or very small numbers using scientific notation.
For example:
big_number = 1.23e100 # 1.23 times 10 to the power of 100
small_number = 1.23e-5 # 1.23 times 10 to the power of -5
Keep in mind that due to the way floating-point numbers are represented in binary, there can be some precision issues when performing certain operations. This is a common source of errors in numerical computations. For critical applications that require precise calculations, you may need to use specialized libraries like decimal
or numpy
that provide more control over precision. To learn more, click here.