Chapter 2 Using Python as a Calculator

2.5 Floating Point Expressions

In computer science, real numbers are typically called floating point numbers.

Regardless of operands, when all the numbers in a Python expression are integers, the expression is an integer expression, and the value of the expression itself is an integer (except division).

However, when there is at least one floating point number in an expression, the expression is a floating point expression, and its value is a floating point number. Below are some more examples, which show that +, − and ∗ operators can all be applied to floating point numbers, resulting in floating point numbers.

As discussed before, the int function takes one argument and converts it into an integer, while the float function takes one argument and converts it into a floating point number.

The int function converts a floating point number into an integer by discarding all the digits after the floating point. For example,

In the last example, the return value of int(3.9) is 3, even though 3.9 is numerically closer to the integer 4. For floating-point conversion by rounding up an integer, the round function can be used.

The round function can round up a number not only to the decimal point, but also to a specific number of digits after the decimal point. In the latter case, two arguments must be given to the function all, with the second input argument indicating the number of digits to keep after the decimal point. The following examples illustrate this use of the round function with more than one input arguments. Take note of the comma that separates two input arguments.

A floating point operator that results in an integer value is the integer division operator (//), which discards any fractional part in the division.

Correspondingly, the modulo operator can also be applied to floating point division.

Another useful function is abs, which takes one numerical argument and returns its absolute value.

One final note on floating point numbers is that their literals can be expressed by a scientific notation. For example,

The notations xey and xEy have the same meaning. They indicate the value of \(x \times 10^y\).

© Copyright 2024 GS Ng.

Next Section - 2.6 Identifiers, Variables and Assignment