Skip to content

Commit

Permalink
Implement first scaling proposal from #997
Browse files Browse the repository at this point in the history
  • Loading branch information
Ivan Mirić committed Feb 28, 2020
1 parent 9cb4ed0 commit 323aa8e
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 15 deletions.
25 changes: 12 additions & 13 deletions lib/execution_segment.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ package lib
import (
"encoding"
"fmt"
"math"
"math/big"
"strings"
)
Expand Down Expand Up @@ -259,27 +260,25 @@ func roundUp(rat *big.Rat) *big.Int {

// Scale proportionally scales the supplied value, according to the execution
// segment's position and size of the work.
// This implements the first proposal from #997:
// floor( (value * from) % 1 + value * length )
func (es *ExecutionSegment) Scale(value int64) int64 {
if es == nil { // no execution segment, i.e. 100%
return value
}
// Instead of the first proposal that used remainders and floor:
// floor( (value * from) % 1 + value * length )
// We're using an alternative approach with rounding that (hopefully) has
// the same properties, but it's simpler and has better precision:
// round( (value * from) - round(value * from) + (value * (to - from)) )?
// which reduces to:
// round( (value * to) - round(value * from) )?

toValue := big.NewRat(value, 1)
toValue.Mul(toValue, es.to)

fromValue := big.NewRat(value, 1)
fromValue.Mul(fromValue, es.from)

toValue.Sub(toValue, new(big.Rat).SetFrac(roundUp(fromValue), oneBigInt))
rem := new(big.Int).Rem(fromValue.Num(), fromValue.Denom())
fromRem := big.NewRat(rem.Int64(), fromValue.Denom().Int64())

lenValue := big.NewRat(value, 1)
lenValue.Mul(lenValue, es.length)

total := new(big.Rat).Add(fromRem, lenValue)

return roundUp(toValue).Int64()
totalf, _ := total.Float64()
return int64(math.Floor(totalf))
}

// InPlaceScaleRat scales rational numbers in-place - it changes the passed
Expand Down
6 changes: 4 additions & 2 deletions lib/execution_segment_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -190,11 +190,13 @@ func TestExecutionSegmentScale(t *testing.T) {
es := new(ExecutionSegment)
require.NoError(t, es.UnmarshalText([]byte("0.5")))
require.Equal(t, int64(1), es.Scale(2))
require.Equal(t, int64(2), es.Scale(3))
require.Equal(t, int64(1), es.Scale(3))
require.Equal(t, int64(5), es.Scale(10))

require.NoError(t, es.UnmarshalText([]byte("0.5:1.0")))
require.Equal(t, int64(1), es.Scale(2))
require.Equal(t, int64(1), es.Scale(3))
require.Equal(t, int64(2), es.Scale(3))
require.Equal(t, int64(5), es.Scale(10))
}

func TestExecutionSegmentCopyScaleRat(t *testing.T) {
Expand Down

0 comments on commit 323aa8e

Please sign in to comment.