Skip to content

fix: sampling a random PrimeField element takes millions of tries - #259

Open
saviourmk wants to merge 1 commit into
pluto:mainfrom
saviourmk:fix/prime-field-sampling
Open

saviourmk wants to merge 1 commit into
pluto:mainfrom
saviourmk:fix/prime-field-sampling

Conversation

@saviourmk

Copy link
Copy Markdown

Sampling a random PrimeField element draws rng.next_u32() >> 4, a 28 bit number, and throws it away unless it's below P. That looks like it came from a field close to 2^31. For the Pluto primes it means 1 in about 2.6 million draws is accepted for PlutoBaseField and 1 in about 16 million for PlutoScalarField, and every rng.gen::<PrimeField<P>>() in the crate and its tests pays for that.

It changes the following:

sample now uses rng.gen_range(0..P), which is still uniform and rejects as few draws as it can. There's a new test that draws 1000 * P elements in both Pluto fields and checks that every value comes up about 1000 times.

In a release build one draw took 38 ms for PlutoScalarField and 4.8 ms for PlutoBaseField on main, and takes 29 ns and 16 ns with this change. The new test runs in 0.1 s here, on main it would take around 20 minutes even in a release build.

This is the fix I mentioned in #258, after this the commitments there could go back to rng.gen().

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant