Skip to content

Commit

Permalink
Fix fft_fr.IsPowerOfTwo(). (Layr-Labs#638)
Browse files Browse the repository at this point in the history
Signed-off-by: Cody Littley <[email protected]>
  • Loading branch information
cody-littley authored Jul 15, 2024
1 parent 647c8cb commit ff3d573
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
7 changes: 4 additions & 3 deletions encoding/fft/fft_fr.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,9 +109,9 @@ func (fs *FFTSettings) InplaceFFT(vals []fr.Element, out []fr.Element, inv bool)
}
if inv {
var invLen fr.Element

invLen.SetInt64(int64(n))

invLen.Inverse(&invLen)
rootz := fs.ReverseRootsOfUnity[:fs.MaxWidth]
stride := fs.MaxWidth / n
Expand All @@ -132,6 +132,7 @@ func (fs *FFTSettings) InplaceFFT(vals []fr.Element, out []fr.Element, inv bool)
}
}

// IsPowerOfTwo returns true if the provided integer v is a power of 2.
func IsPowerOfTwo(v uint64) bool {
return v&(v-1) == 0
return (v&(v-1) == 0) && (v != 0)
}
21 changes: 21 additions & 0 deletions encoding/fft/fft_fr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
package fft

import (
"math"
"testing"

"github.com/consensys/gnark-crypto/ecc/bn254/fr"
Expand Down Expand Up @@ -100,3 +101,23 @@ func TestInvFFT(t *testing.T) {
assert.True(t, res[i].Equal(&expected[i]))
}
}

func TestIsPowerOfTwo(t *testing.T) {
var i uint64
for i = 0; i <= 1024; i++ {
result := IsPowerOfTwo(i)

var expectedResult bool
if i == 0 {
// Special case: math.Log2() is undefined for 0
expectedResult = false
} else {
// If a number is not a power of two then the log base 2 of that number will not be a whole integer.
logBase2 := math.Log2(float64(i))
truncatedLogBase2 := float64(uint64(logBase2))
expectedResult = logBase2 == truncatedLogBase2
}

assert.Equal(t, expectedResult, result, "IsPowerOfTwo(%d) returned unexpected result '%t'.", i, result)
}
}

0 comments on commit ff3d573

Please sign in to comment.