Fall 2024 - P4
Big Idea 3 | .1 | .2 | .3 | .4 | .5 | .6 | .7 | .8 | .10 |
3.2 Lesson Period 4 - Float Data Abstraction
Floating - 3.2.2
A floating-point number (or simply “float”) in Python is a data type used to represent real numbers that have a decimal point. Floats can represent numbers with a fractional part, making them useful for more precise calculations than integers. Python uses double precision to store floating-point numbers, which means they are accurate to about 15 decimal places.
Purpose
- Represent numbers with a decimal point (e.g., 3.14, -0.001, 2.0).
- Used for calculations requiring fractional values or more precision than integers.
- Support arithmetic operations similar to integers but with decimal precision.
- Useful for scientific calculations, statistics, and data analysis.
- Can represent very large or very small numbers using scientific notation (e.g.,
1.2e10
). - Important in division operations, where the result might not be a whole number.
Example
# Defining floating-point numbers
x = 10.5
y = -3.14
# Performing arithmetic operations with floats
sum_of_floats = x + y
product_of_floats = x * y
print("Sum:", sum_of_floats) # Output: 7.36
print("Product:", product_of_floats) # Output: -32.97
# Using floats in mathematical functions
import math
z = 16.0
print("Square root of z:", math.sqrt(z)) # Output: 4.0
Sum: 7.359999999999999
Product: -32.97
Square root of z: 4.0
Javascript Version
// Defining floating-point numbers
let x = 10.5;
let y = -3.14;
// Performing arithmetic operations with floats
let sumOfFloats = x + y;
let productOfFloats = x * y;
console.log("Sum:", sumOfFloats); // Output: 7.36
console.log("Product:", productOfFloats); // Output: -32.97
// Using floats in mathematical functions
let z = 16.0;
console.log("Square root of z:", Math.sqrt(z)); // Output: 4.0