Fall 2024 - P4
Big Idea 3 | .1 | .2 | .3 | .4 | .5 | .6 | .7 | .8 | .10 |
3.2 Float
Floating in python
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.
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
%%js
// 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
<IPython.core.display.Javascript object>