Skip to content

ACP: More float constants #661

@joshuarayton

Description

@joshuarayton

Proposal

Implement more float constants, namely: sqrt(5), 1/sqrt(5), ln(3)

Problem statement

The need for using floating point representations of the numerical constants.

Motivating examples or use cases

Constant time generation of Fibonacci numbers

#![feature(f128)]
#![feature(more_float_constants)]

use std::f128::consts::PHI;

const FRAC_1_SQRT_5: f128 =
    0.447213595499957939281834733746255247088123671922305144854179_f128;

fn fib(n: i32) -> u64 {
    return (FRAC_1_SQRT_5 * PHI.powi(n)).round() as u64
}

pub fn main() {
    for n in 1..94 {
        println!("{}", fib(n));
    }
}

Generates all Fibonacci numbers that fit in u64

Solution sketch

In core/src/num/f32.rs:

pub mod consts {
    // ...

    // sqrt(5)
    pub const SQRT_5: f32 = 2.236067977499789696409173668731276235_f32;

    // 1/sqrt(5)
    pub const FRAC_1_SQRT_5: f32 = 0.447213595499957939281834733746255247_f32;

    // ln(3)
    pub const LN_3: f32 = 1.098612288668109691395245236922525704_f32;

    // ...
}

Basically the same in f64.rs, f16.rs, f128.rs

Alternatives

Links and related work

rust-lang/rust#146934
rust-lang/rust#146939
rust-lang/rust#103883
rust-lang/rust#125253
rust-lang/rust#116909
#383
#119

Metadata

Metadata

Assignees

No one assigned

    Labels

    ACP-acceptedAPI Change Proposal is accepted (seconded with no objections)T-libs-apiapi-change-proposalA proposal to add or alter unstable APIs in the standard libraries

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions