2 Questions on `std::f64::consts::PI`

Hello :crab: , I have 2 questions regarding std::f64::consts::PI

Q1 : Is there a benefit (or motivation) behind specifying more than 14 digits below radix point for PI ?

According to the results I got from this experiment (in Rust Playground), specifying 14 digits (in base 10) below radix point in code seems "enough" when storing a PI constant as f64, since writing more digits doesn't affect the bit-level representation.

Meanwhile the definition of std::f64::consts::PI specifies 35 digits below radix point in code.

// (from rust/library/core/src/num/f64.rs)

pub const PI: f64 = 3.14159265358979323846264338327950288_f64;

Q2 : Confusing comment shown in docs page of PI

Docs page for std::f64::consts::PI displays the definition of PI constant as below:

pub const PI: f64 = 3.14159265358979323846264338327950288f64; // 3.1415926535897931f64

What confuses me is the comment at the end of the line.
It specifies only 16 digits below radix point and the 16th digit ("1") differs from the 16th digit of the value stored to PI in code ("0").

Rounding the PI constant to the 16th digit doesn't result in the value specified in the comment.

When I looked at the source (by clicking the source button in the docs page), I couldn't find such comment in the same file.

How is that comment generated? What information does it intend to give us?


Thank you in advance! :crab:

The number used dates from ancient history (for Rust), and was probably just copy-pasted from some C long double definition.

The comment is added by rustdoc and I guess it's from const evaluation but can't explain the exact discrepancy in the example. Maybe it's a printing issue? Just guessing.

3 Likes

17 significant digits is always sufficient to round-trip an f64.

It probably has more digits because it doesn't hurt anything, and just copying it from some other reference with obviously more than enough digits is more clearly correct than something carefully truncated.

The actual value of PI is not π, it's https://float.exposed/0x400921fb54442d18, which sin confirms is slightly below π.

Anything between about 3.1415926535897929 and 3.1415926535897933 will give the same value as std::f64::consts::PI. (For comparison, actual π is 3.1415926535897932…)

It looks like the docs probably show 17 sigfigs -- picked as mentioned above. Curiously that's more than needed to round-trip this particular value, as the Debug impl would give 3.141592653589793_f64 instead. (More digits is still in that above range, so isn't actually meaningful.)

6 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.