Tired of defining your own golden ratio or Euler-Mascheroni constant? As of Rust 1.94, std ships them out of the box — no more copy-pasting magic numbers.
Before: Roll Your Own
If you needed the golden ratio or the Euler-Mascheroni constant before Rust 1.94, you had to define them yourself:
1
2
| const PHI: f64 = 1.618033988749895;
const EULER_GAMMA: f64 = 0.5772156649015329;
|
This works, but it’s error-prone. One wrong digit and your calculations drift. And every project that needs these ends up with its own slightly-different copy.
After: Just Use std
Rust 1.94 added GOLDEN_RATIO and EULER_GAMMA to the standard consts modules for both f32 and f64:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| use std::f64::consts::{GOLDEN_RATIO, EULER_GAMMA};
fn main() {
// Golden ratio: (1 + √5) / 2
let phi = GOLDEN_RATIO;
assert!((phi * phi - phi - 1.0).abs() < 1e-10);
// Euler-Mascheroni constant
let gamma = EULER_GAMMA;
assert!((gamma - 0.5772156649015329).abs() < 1e-10);
println!("φ = {phi}");
println!("γ = {gamma}");
}
|
These sit right alongside the constants you already know — PI, TAU, E, SQRT_2, and friends.
Where You’d Actually Use Them
Golden ratio shows up in algorithm design (Fibonacci heaps, golden-section search), generative art, and UI layout proportions:
1
2
3
4
5
6
7
8
9
10
11
12
| use std::f64::consts::GOLDEN_RATIO;
fn golden_section_dimensions(width: f64) -> (f64, f64) {
let height = width / GOLDEN_RATIO;
(width, height)
}
fn main() {
let (w, h) = golden_section_dimensions(800.0);
assert!((w / h - GOLDEN_RATIO).abs() < 1e-10);
println!("Width: {w}, Height: {h:.2}");
}
|
Euler-Mascheroni constant appears in number theory, harmonic series approximations, and probability:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| use std::f64::consts::EULER_GAMMA;
/// Approximate the N-th harmonic number using the
/// asymptotic expansion: H_n ≈ ln(n) + γ + 1/(2n)
fn harmonic_approx(n: u64) -> f64 {
let nf = n as f64;
nf.ln() + EULER_GAMMA + 1.0 / (2.0 * nf)
}
fn main() {
// Exact H_10 = 1 + 1/2 + 1/3 + ... + 1/10
let exact: f64 = (1..=10).map(|i| 1.0 / i as f64).sum();
let approx = harmonic_approx(10);
println!("Exact H_10: {exact:.6}");
println!("Approx H_10: {approx:.6}");
assert!((exact - approx).abs() < 0.01);
}
|
The Full Lineup
With these additions, std::f64::consts now includes: PI, TAU, E, SQRT_2, SQRT_3, LN_2, LN_10, LOG2_E, LOG2_10, LOG10_2, LOG10_E, FRAC_1_PI, FRAC_1_SQRT_2, FRAC_1_SQRT_2PI, FRAC_2_PI, FRAC_2_SQRT_PI, FRAC_PI_2, FRAC_PI_3, FRAC_PI_4, FRAC_PI_6, FRAC_PI_8, GOLDEN_RATIO, and EULER_GAMMA. That’s a pretty complete toolkit for numerical work — all with full f64 precision, available at compile time.