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

Fix fft_fr.IsPowerOfTwo(). (#83) #638

Merged
merged 3 commits into from
Jul 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}
}
Loading