Skip to content

Commit

Permalink
Replace crypto/rand to math/rand/v2
Browse files Browse the repository at this point in the history
  • Loading branch information
itsubaki committed Apr 6, 2024
1 parent 8b053f3 commit 54f1fb2
Show file tree
Hide file tree
Showing 7 changed files with 83 additions and 143 deletions.
13 changes: 0 additions & 13 deletions math/rand/const.go

This file was deleted.

39 changes: 0 additions & 39 deletions math/rand/const_test.go

This file was deleted.

33 changes: 0 additions & 33 deletions math/rand/crypto.go

This file was deleted.

56 changes: 0 additions & 56 deletions math/rand/crypto_test.go

This file was deleted.

31 changes: 30 additions & 1 deletion math/rand/math.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,34 @@
package rand

import "math/rand/v2"
import (
"math/rand/v2"

"github.com/itsubaki/q/math/number"
)

var Float64 = rand.Float64

// Const returns a constant number in [0.0, 1.0).
func Const(seed ...uint64) func() float64 {
var s0, s1 uint64
if len(seed) > 0 {
s0 = seed[0]
}

if len(seed) > 1 {
s1 = seed[1]
}

return rand.New(rand.NewPCG(s0, s1)).Float64
}

// Coprime returns a random coprime number in [2, N).
func Coprime(N int) int {
min, max := 2, N-2
for {
a := rand.N(max-1) + min
if number.GCD(N, a) == 1 {
return a
}
}
}
52 changes: 52 additions & 0 deletions math/rand/math_test.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,54 @@
package rand_test

import (
"fmt"
"testing"

"github.com/itsubaki/q/math/rand"
)

func ExampleCoprime() {
p := rand.Coprime(15)

for _, e := range []int{2, 4, 7, 8, 11, 13, 14} {
if p == e {
fmt.Println("found")
break
}
}

// Output:
// found
}

func ExampleConst() {
c := rand.Const()
fmt.Printf("%.13f\n", c())
fmt.Printf("%.13f\n", c())
fmt.Printf("%.13f\n", c())
fmt.Printf("%.13f\n", rand.Const(1)())
fmt.Printf("%.13f\n", rand.Const(1)())
fmt.Printf("%.13f\n", rand.Const(1)())
fmt.Printf("%.13f\n", rand.Const(2)())
fmt.Printf("%.13f\n", rand.Const(3)())
fmt.Printf("%.13f\n", rand.Const(1, 0)())
fmt.Printf("%.13f\n", rand.Const(1, 1)())
fmt.Printf("%.13f\n", rand.Const(1, 2)())

// Output:
// 0.9999275824803
// 0.8856419373529
// 0.3814775277115
// 0.2384231908739
// 0.2384231908739
// 0.2384231908739
// 0.8269781200925
// 0.8353847703964
// 0.2384231908739
// 0.3402859786606
// 0.6764556596678
}

func TestFloat64(t *testing.T) {
r := rand.Float64()
if r >= 0 && r < 1 {
Expand All @@ -14,3 +57,12 @@ func TestFloat64(t *testing.T) {

t.Fail()
}

func TestConst(t *testing.T) {
r := rand.Const()()
if r >= 0 && r < 1 {
return
}

t.Fail()
}
2 changes: 1 addition & 1 deletion quantum/qubit/qubit.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ type Qubit struct {
func New(z ...complex128) *Qubit {
q := &Qubit{
vector: vector.New(z...),
Rand: rand.Crypto(),
Rand: rand.Float64,
}

q.Normalize()
Expand Down

0 comments on commit 54f1fb2

Please sign in to comment.