Repository navigation
fix(optimizer): add sum([...]) elements left to right - #999
Open
waw666waw666 wants to merge 1 commit into
Open
waw666waw666 wants to merge 1 commit into
waw666waw666 wants to merge 1 commit into
Conversation
The sum array optimization rewrote sum([a, b, c]) as a + (b + c), while the sum builtin adds the elements in order. Float addition is not associative, so the optimized program could return a different value: with a = 1e16, b = -1e16, c = 1 it returned 0 instead of 1, and sum([x, y, z]) == x + y + z was false for 0.1, 0.2, 0.3. Build ((a + b) + c) instead, which matches the runtime order.
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
The
sum([...])optimization rewritessum([a, b, c])asa + (b + c). Thesumbuiltin adds the elements in order, so the optimized program groups float additions differently and can return a different value than the same expression withexpr.Optimize(false):Literal arrays are folded into a constant before this pass, so the rewrite only applies when the elements are variables or other expressions.
Cause:
sumArrayFoldbuilt the+chain recursively from the right. Float addition is not associative, soa + (b + c)and(a + b) + ccan differ.Fix: build the chain from the left,
((a + b) + c) + ..., which is the order thesumloop adds in. For ints nothing changes. Wrap-around on overflow gives the same result in any grouping.Tests:
TestOptimize_sum_array_3now expects(a + b) + c.TestOptimize_sum_array_float_orderchecks the three expressions above against the expected values and against the same program compiled withexpr.Optimize(false). It fails on master and passes with this change.go test ./...,go vet ./...andgofmtall pass. Theexpr_debugdebugger test also passes.