Floating point types in Rust - Time & Space Complexity
When working with floating point types in Rust, it's helpful to understand how operations on these numbers affect program speed.
We want to know how the time to do calculations changes as we work with more floating point numbers.
Analyze the time complexity of the following code snippet.
fn sum_floats(numbers: &[f64]) -> f64 {
let mut total = 0.0;
for &num in numbers {
total += num;
}
total
}
This code adds up all the floating point numbers in a list and returns the total.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding each floating point number to a running total.
- How many times: Once for each number in the input list.
As the list gets longer, the number of additions grows directly with the number of items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows in a straight line as the input size increases.
Time Complexity: O(n)
This means the time to add all numbers grows directly with how many numbers there are.
[X] Wrong: "Floating point operations take constant time no matter what, so time complexity doesn't matter."
[OK] Correct: While each addition is fast, doing many additions still takes more time as the list grows, so total time depends on input size.
Understanding how operations on floating point numbers scale helps you explain performance clearly and shows you can think about efficiency in real code.
"What if we changed the code to multiply all numbers instead of adding? How would the time complexity change?"