Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

x/website: SumNumbers depends on map iteration order with float64 #51715

Open
niaow opened this issue Mar 16, 2022 · 1 comment
Open

x/website: SumNumbers depends on map iteration order with float64 #51715

niaow opened this issue Mar 16, 2022 · 1 comment
Labels
Documentation NeedsDecision website
Milestone

Comments

@niaow
Copy link

@niaow niaow commented Mar 16, 2022

What version of Go are you using (go version)?

Go 1.18 via playground.

What did you do?

I added extreme float64 values to the input of the SumNumbers function from https://go.dev/doc/tutorial/generics.

https://go.dev/play/p/aQ1cotOVsEc

What did you expect to see?

The function returns the same value consistently.

What did you see instead?

Across 4 runs:

0 62.97 35.98 0

Re-running this may provide different results.

The function works correctly with int64 because integer addition is associative. Addition is not associative with float64 values, so the map order changes the result dramatically.

@gopherbot gopherbot added this to the Unreleased milestone Mar 16, 2022
@ALTree
Copy link
Member

@ALTree ALTree commented Mar 16, 2022

On one hand, I agree the example is unfortunate, in that map iteration is not deterministic and thus in the float64 case the procedure exhibits numerical instability... on the other hand, it's supposed to be a quick introduction to type parameters. The kind of people that may care about the algorithm's numerical stability also probably understand that the example is not meant to be used in a numerical simulation in production.

I don't think it's worthwhile to add code to sort the map. Replacing a map with a slice would also fix the issue, but then we would lose the chance to also show what comparable is (it's used in the signature as K comparable).

@ALTree ALTree added Documentation NeedsDecision labels Mar 16, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Documentation NeedsDecision website
Projects
None yet
Development

No branches or pull requests

3 participants