Int vs Float in C++
Int vs Float in C++
Int vs Float in C++: Performance-Oriented Data Type Choice
Prerequisites
1. Why Data Type Choice Matters
Not all numeric types are equal in performance.
The type you choose affects:
- CPU execution speed
- Precision
- Cache efficiency
- Overall performance
If exact floating-point values are NOT required, prefer integer-based computation
| Feature | int | float |
|---|---|---|
| Precision | Exact | Approximate |
| Speed | Faster (generally) | Slower (depends on hardware) |
| Determinism | High | Low (rounding errors) |
| Comparison | Reliable | Risky |
2. Int vs Float
✔ Reasons of using Int
- Simpler CPU instructions
- No rounding / normalization
- Better predictability
- Often lower latency
Comparison Problem with Float
❌ Unsafe
1
2
3
4
if (a == b)
{
// may fail due to precision error
}
✔ Safer
1
2
3
4
if (fabs(a - b) < 1e-6)
{
// approximate comparison
}
Extra computation required → slower
3. Replace Float with Int (Scaling Technique)
Convert float to scaled integer
1
2
float value = 3.14f;
int scaled = (int)(value * 100); // 314
Now compare as integer:
1
2
3
4
if (scaled > 300)
{
// fast integer comparison
}
❌ Float-based
1
2
3
4
if (distance < 1.5f)
{
// ...
}
✔ Int-based
1
2
3
4
5
int dist_scaled = distance * 100;
if (dist_scaled < 150)
{
// ...
}
Faster + deterministic
3-1. When to Prefer int
✔ Only comparison matters
✔ Fixed precision acceptable
✔ Performance-critical loops
✔ Large-scale data processing
3-2. When to Prefer float
✔ Real-world measurement
✔ Continuous values
✔ Scientific / graphics computation
✔ High precision required
| Approach | Pros | Cons |
|---|---|---|
int | Fast, deterministic | Limited range/precision |
float | Flexible, expressive | Slower, precision issues |
This post is licensed under CC BY 4.0 by the author.