Example #1
0
File: ac.go Project: postfix/ctw
// expTables prepares the exp-tables described in section 6.4 of the EIDMA report by F.M.J. Willems and Tj. J. Tjalkens.
// Complexity Reduction of the Context-Tree Weighting Algorithm: A Study for KPN Research, Technical University of Eindhoven, EIDMA Report RS.97.01
func expTables() ([]uint64, []uint64) {
	var pow2f float64 = 1 << f
	A := make([]uint64, int(pow2f)+1)
	for i := 1; i <= int(pow2f); i++ {
		A[i] = uint64(pow2f*math.Exp2(-float64(i)/pow2f) + 0.5)
	}

	// B entries for (1<<(f-1)), (1<<f)-1
	B := make([]uint64, int(pow2f))
	for j := 1 << (f - 1); j <= (1<<f)-1; j++ {
		B[j] = uint64(-pow2f*math.Log2(float64(j)/pow2f) + 0.5)
	}

	// B entries for 1,(1<<(f-1))-1
	for j := 1; j < (1 << (f - 1)); j++ {
		k := math.Ceil(float64(f) - 1 - math.Log2(float64(j)))
		b2kj := B[int(math.Exp2(k))*j]
		if b2kj == 0 {
			panic("")
		}
		B[j] = b2kj + uint64(k*pow2f)
	}

	return A, B
}
Example #2
0
func main() {
	var err error

	workerCount, err = strconv.Atoi(os.Getenv("GOMAXPROCS"))
	if err != nil {
		workerCount = 1
	}

	var nClauses, nVar int

	fmt.Scanf("%d %d", &nClauses, &nVar)

	clauses := readClauses(nClauses, nVar)

	startTime := time.Now()

	solution := solveClauses(clauses, nClauses, nVar)

	if solution >= 0 {
		fmt.Printf("Solution found [%d]: ", solution)
		for i := 0; i < nVar; i++ {
			fmt.Printf("%d ", int64(float64(solution&int64(math.Exp2(float64(i))))/math.Exp2(float64(i))))
		}
		fmt.Printf("\n")
	} else {
		fmt.Printf("Solution not found.\n")
	}

	duration := time.Since(startTime)
	fmt.Println("Duration: ", duration)
}
Example #3
0
func solveClauses(clauses [][]int8, nClauses, nVar int) int64 {
	iVar = make([]int64, nVar)
	for i := 0; i < nVar; i++ {
		iVar[i] = int64(math.Exp2(float64(i)))
	}
	maxNumber = int64(math.Exp2(float64(nVar)))

	ch := make(chan int64)
	for i := 0; i < workerCount; i++ {
		go clauseSolverWorker(clauses, nClauses, i, ch)
	}

	var solution int64 = -1
	for i := 0; i < workerCount; i++ {
		solution = <-ch
		if solution < 0 {
			continue
		} else {
			fmt.Println(solution)
			break
		}
	}

	return solution
}
Example #4
0
// Random gamma variable when shape<1
// See Kundu and Gupta 2007
// "A convenient way of generating gamma random variables using generalized exponential distribution"
func (rg RandGen) rgamma2(shape float64) float64 {
	if shape <= 0.0 || shape >= 1.0 {
		panic("Illegal parameter. Shape must be positive and no greater than one")
	}

	d := 1.0334 - 0.0766*math.Exp(2.2942*shape) // Constants from paper
	a := math.Exp2(shape) * math.Pow(-math.Expm1(-d/2), shape)
	pdsh := math.Pow(d, shape-1.0)
	b := shape * pdsh * math.Exp(-d)
	c := a + b

start:
	u := rg.Float64()
	var x float64
	if u <= a/c {
		x = -2.0 * math.Log1p(-math.Pow(c*u, 1.0/shape)/2.0)
	} else {
		x = -math.Log(c * (1.0 - u) / (shape * pdsh))
	}
	v := rg.Float64()
	if x <= d {
		p := math.Pow(x, shape-1.0) * math.Exp(-x/2.0) / (math.Exp2(shape-1.0) * math.Pow(-math.Expm1(-x/2.0), shape-1.0))
		if v > p {
			goto start
		}
	} else {
		if v > math.Pow(d/x, 1.0-shape) {
			goto start
		}
	}

	return x
}
Example #5
0
// errorWithPrecision returns the error range in latitude and longitude for in
// integer geohash with bits of precision.
func errorWithPrecision(bits uint) (latErr, lngErr float64) {
	latBits := bits / 2
	lngBits := bits - latBits
	latErr = 180.0 / math.Exp2(float64(latBits))
	lngErr = 360.0 / math.Exp2(float64(lngBits))
	return
}
Example #6
0
func (s *song) next() (n int, freq float64) {
	if len(s.tones) == 0 {
		s.last = s.center
		return 1, s.last
	}
	cSum, ampSum := s.partialComplexity()
	sum := 0.0
	sums := make([]float64, len(rats))
	for i, r := range rats {
		p := math.Log2(s.last * r.float() / s.center)
		sum += math.Exp2(-p*p/2) * math.Exp2(-s.complexityWith(cSum, ampSum, r))
		sums[i] = sum
	}
	i := 0
	x := sum * rand.Float64()
	for i = range sums {
		if x < sums[i] {
			break
		}
	}
	r := rats[i]
	s.last *= r.float()
	r.a *= s.tones[len(s.tones)-1].n
	for _, t := range s.tones {
		t.n *= r.b
	}
	return r.a, s.last
}
Example #7
0
func (m *Melody) newFrequency() ratio {
	harmonies := make([]int, len(m.history))
	for i, n := range m.history {
		harmonies[i] = n.f
	}
	return selectRatio(func(r ratio) float64 {
		dp := math.Log2(m.lastFrequency * r.float() / m.avgFrequency)
		return math.Exp2(-dp*dp/2) * math.Exp2(m.frequencyBias*m.frequencyComplexity(harmonies, r))
	})
}
Example #8
0
func digitsSignature(n int) int {
	r := 0
	for n != 0 {
		d := n - (n/10)*10
		if (r & int(math.Exp2(float64(d)))) == 0 {
			r += int(math.Exp2(float64(d)))
		}
		n = (n - d) / 10
	}
	return r
}
Example #9
0
func (s *song) partialComplexity() (cSum, ampSum float64) {
	for _, t1 := range s.tones {
		a1 := math.Exp2(t1.amp)
		for _, t2 := range s.tones {
			a2 := math.Exp2(t2.amp)
			cSum += a1 * a2 * float64(complexity(t1.n, t2.n))
		}
		ampSum += a1
	}
	return
}
Example #10
0
func (v *voice) Sing() float64 {
	p := math.Exp2(v.Pitch.Sing())
	r := math.Exp2(v.Amp.Sing()) * v.rand.NormFloat64()
	if v.Pitch.Done() && v.Amp.Done() {
		r = 0
	}
	c := v.b*v.b/4 + 4*math.Pi*math.Pi*p*p
	v.u += v.dt*v.v + v.sqdt*r
	v.v -= v.dt * (v.b*v.v + c*v.u)
	v.RMS.Add(v.u)
	return v.u
}
Example #11
0
// Given the time stamp, decay the scores
func (ts *territoryScore) decay(now *time.Time) {
	// The decay is based on an exponential half time
	deltaTime := float64(now.Sub(ts.TimeStamp))
	ts.TimeStamp = *now
	ts.modified = true

	// Update decay of Score
	ts.Score *= math.Exp2(-deltaTime / float64(ConfigScoreHalfLife))

	// Update the decay of ScoreBalance. Subtract the offset before doing the decay, and add it
	// back again afterwards.
	bal := ts.ScoreBalance - ConfigScoreBalanceZero
	ts.ScoreBalance = bal*math.Exp2(-deltaTime/float64(ConfigScoreBalHalfLife)) + ConfigScoreBalanceZero
}
Example #12
0
func (this *defCodec) encodeHead2(b []byte) {
	if ln := len(b) - 2; ln <= (int(math.Exp2(16))-1) && ln <= this.maxPacketSize {
		this.byteOrder.PutUint16(b, uint16(ln))
	} else {
		panic(ErrCodecTooLarge)
	}
}
Example #13
0
// add two numbers without using arithmetic operators
func Add(x, y uint32) uint32 {
	var answer uint32
	var carry bool
	// function to return either 0 or 1, the bit of `num` at `position`

	for i := 0; i < 32; i++ {
		var b uint32 = uint32(math.Exp2(float64(i))) // need to do some casting and this syntax is likely wrong
		if (b&x)&(b&y) > 0 {
			if carry == true {
				answer = answer | b
			}
			carry = true
		} else if (b&x)|(b&y) > 0 {
			if carry == false {
				answer = answer | b
			}
		} else {
			if carry == true {
				answer = answer | b
			}
			carry = false
		}
	}
	return answer
}
Example #14
0
func calculateVanityAddressStuff(vad VanityAddressData) VanityAddressData {
	answer := vad
	var complexity float64 = 1.0
	var lavishness float64 = 1.0
	var bounty float64 = answer.Bounty

	pattern := answer.Pattern[1:]

	countingOnes := true
	for i := 0; i < len(pattern); i++ {
		if countingOnes {
			if pattern[i] == '1' {
				complexity *= 256
			} else {
				complexity *= 58
				countingOnes = false
			}
		} else {
			complexity *= 58
		}
	}

	lavishness = math.Exp2(32.0) * bounty / complexity

	answer.Complexity = complexity
	answer.Lavishness = lavishness
	answer.ComplexityStr = fmt.Sprintf("%g", complexity)
	answer.LavishnessStr = fmt.Sprintf("%g", lavishness)
	answer.BountyStr = fmt.Sprintf("%.8g", bounty)
	return answer
}
//Hash function for IP:Port, Key and Rel
func hashIt(s string, bit int) int {
	h := sha1.New()
	h.Write([]byte(s))
	bs := h.Sum(nil)
	hashValue := math.Mod(float64(bs[len(bs)-1]), math.Exp2(float64(bit)))
	return int(hashValue)
}
Example #16
0
// generate a topology section by creating height values between 1 and -1 for each
// element. Zoom, xoff and yoff can be used to create adjacent topolgy sections
// that seemlessly stitch together. The final topology section is the result of
// multiple generated simplex noise (2nd gen Perlin) combined as fractional
// brownian motion.
//
// Zoom, xoff, yoff are combined to indicate the location of the topology section
// within an overall world. Zoom increases the number of land sections needed
// for the world.
//   Zoom level 0 :     1 topology sections
//   Zoom level 1 :     4 topology sections indexed 0,0 to 1,1
//   Zoom level 2 :    16 topology sections indexed 0,0 to 3,3
//   Zoom level 3 :    64 topology sections indexed 0,0 to 7,7
//   Zoom level 4 :   256 topology sections indexed 0,0 to 15,15
//   Zoom level 5 :  1024 topology sections indexed 0,0 to 31,31
//   Zoom level 6 :  4096 topology sections indexed 0,0 to 63,63
//   Zoom level 7 : 16384 topology sections indexed 0,0 to 127,127
//   Zoom level 8 : 65536 topology sections indexed 0,0 to 255,255
func (t Topo) generate(zoom, xoff, yoff uint, n *noise) {
	freq := 2.0           // overall size.
	gain := 0.55          // range of heights.
	octaves := 6 + zoom*2 // feature sharpness
	lacunarity := 2.0     // feature scatter
	zexp := math.Exp2(float64(zoom))
	size := float64(len(t))
	for y := range t {
		for x := range t[y] {
			total := 0.0
			xfreq := freq / size
			yfreq := freq / size
			amplitude := gain
			for o := uint(0); o < octaves; o++ {
				xval := float64(x)*xfreq + float64(xoff)*size*xfreq
				yval := float64(y)*yfreq + float64(yoff)*size*yfreq
				total += n.generate(xval/zexp, yval/zexp) * amplitude
				xfreq *= lacunarity
				yfreq *= lacunarity
				amplitude *= gain
			}
			t[x][y] = total
		}
	}
}
Example #17
0
func (k *pressedKey) press(loc geom.Point) {
	if k.voice == nil || k.voice.Done() {
		k.voice = newPressedTone(math.Exp2(k.pitch))
		tones.Add(k.voice)
	}
	updateKeys(k.ratio)
}
Example #18
0
// LegendrePolynomial returns P_n(x) where P_n is the nth degree legendre polynomial
func LegendrePolynomial(n int, x float64) float64 {
	var sum float64
	for k := 0; k <= n; k++ {
		sum += math.Pow(BinomialCoefficient(n, k), 2.0) * math.Pow(x-1.0, float64(n-k)) * math.Pow(x+1, float64(k))
	}
	return math.Exp2(-float64(n)) * sum
}
Example #19
0
/*
* 编码头信息函数
 */
func (this *defCodec) encodeHead1(b []byte) {
	if ln := len(b) - 1; ln <= (int(math.Exp2(8))-1) && ln <= this.maxPacketSize {
		b[0] = byte(ln)
	} else {
		panic(ErrCodecTooLarge)
	}
}
Example #20
0
func init() {
	exp2 = make([]float64, exp2Len)
	for i := range exp2 {
		f := float64(i)/exp2Factor - exp2Offset
		exp2[i] = math.Exp2(f)
	}
}
Example #21
0
func (g *getter) retryRequest(method, urlStr string, body io.ReadSeeker) (resp *http.Response, err error) {
	for i := 0; i < g.c.NTry; i++ {
		time.Sleep(time.Duration(math.Exp2(float64(i))) * 100 * time.Millisecond) // exponential back-off
		var req *http.Request
		req, err = http.NewRequest(method, urlStr, body)
		if err != nil {
			logger.debugPrintf("NewRequest error on attempt %d: retrying url: %s, error: %s", i, urlStr, err)
			return
		}
		g.b.Sign(req)
		resp, err = g.c.Client.Do(req)

		// This is a completely successful request. We check for non error, non nil respond and OK status code.
		// return without retrying.
		if err == nil && resp != nil && resp.StatusCode == 200 {
			return
		}

		logger.debugPrintf("Client error on attempt %d: retrying url: %s, error: %s", i, urlStr, err)

		if body != nil {
			if _, err = body.Seek(0, 0); err != nil {
				logger.debugPrintf("retryRequest body ERROR", errgo.Mask(err))
				return
			}
		}
	}
	return
}
Example #22
0
func Deg2num(lng, lat float64, zoom int) (x, y int) {
	n := math.Exp2(float64(zoom))
	x = int(math.Floor((lng + 180.0) / 360.0 * n))
	lat_rad := lat * math.Pi / 180
	y = int(math.Floor((1.0 - math.Log(math.Tan(lat_rad)+1.0/math.Cos(lat_rad))/math.Pi) / 2.0 * n))
	return
}
Example #23
0
File: prob.go Project: sevki/Posts
func main() {
	n := math.Exp2(16)
	k := 1000
	x := float64((-1*k)*(k-1)) / float64(2*n)
	fmt.Printf("%v", 1-math.Exp(x))

}
Example #24
0
// Gets the next delay in milliseconds and increments the internal try counter.
func (rc *Backoff) NextDelay() time.Duration {
	rc.InitDefaults()

	if rc.MaxTries != 0 && rc.CurrentTry >= rc.MaxTries {
		return time.Duration(0)
	}

	initialDelay := float64(rc.InitialDelay)
	maxDelay := float64(rc.MaxDelay)
	maxDelayAfterTries := float64(rc.MaxDelayAfterTries)
	currentTry := float64(rc.CurrentTry)

	// [from backoff.c]
	k := math.Log2(maxDelay/initialDelay) / maxDelayAfterTries
	d := time.Duration(initialDelay * math.Exp2(currentTry*k))
	rc.CurrentTry++

	if d > rc.MaxDelay {
		d = rc.MaxDelay
	}

	if rc.Jitter != 0 {
		f := (randr.Float64() - 0.5) * 2 // random value in range [-1,1)
		d = time.Duration(float64(d) * (1 + rc.Jitter*f))
	}

	return d
}
Example #25
0
func (k *pluckedKey) release(loc geom.Point) {
	amp := math.Max(-6, math.Log2(math.Tanh(dist(loc, k.pressLoc)/64)))

	updateKeys(k.ratio)
	v := newPluckedTone(amp, math.Exp2(k.pitch))
	tones.Add(v)
	k.keyBase.voice = v
}
Example #26
0
// hf is when the thing you want to estimate will decay in half (halflife)
func MakeHfExpRateEstimator(hf float64, t float64) *HfExponentialRateEstimator {
	res := new(HfExponentialRateEstimator)
	res.p = math.Exp2(-1.0 / hf)
	res.last = t
	res.s = 0
	res.w = 0
	return res
}
Example #27
0
func (s *song) complexityWith(cSum, ampSum float64, r ratio) float64 {
	a1 := 1.0
	t1n := r.a * s.tones[len(s.tones)-1].n
	for _, t2 := range s.tones {
		cSum += a1 * math.Exp2(t2.amp) * float64(complexity(t1n, t2.n*r.b))
	}
	return (cSum + a1*a1) / (ampSum + a1)
}
Example #28
0
// wordlength=size of the constellation, modetype does not matter
func (m *Modem) Init(wordlength int, modetype string) {
	m.bitsPerSymbol = wordlength
	m.modetype = modetype
	switch wordlength {
	case 1:
		m.modetype = "BPSK"
	case 2:
		m.modetype = "QPSK"
		m.offset = math.Pi / 4.0
	case 3:
		m.modetype = "8PSK"
	case 4:
		m.modetype = "16PSK"
	case 8:
		m.modetype = "256QAM"

		n := int64(123)
		str := strconv.FormatInt(n, 2)
		fmt.Println("\n")
		var bitvec = make([]int, 8)
		for indx, _ := range str {
			bitvec[indx], _ = strconv.Atoi(string(str[indx]))

		}

		//Symbol=	{(1-2bi)[8-(1-2bi+2)[4-(1-2bi+4)[2-(1-2bi+6)]]]                +j(1-2bi+1)[8-(1-2bi+3)[4-(1-2bi+5)[2-(1-2bi+7)]]]}
		// realvalue:=(1-2*bitvec[0])*(8-(1-2*bitvec[2])*(4-(1-2*bitvec[4])*(2-(1-2*bitvec[6]))));
		// realvalue:=(1-2*bitvec[0])*(-8-(1-2*bitvec[2])*(4-(1-2*bitvec[4])*(2-(1-2*bitvec[6]))));
		realvalue := (1.0 - 2.0*bitvec[0]) * (8 - (1-2*bitvec[2])*(4-(1-2*bitvec[4])*(2-(1-2*bitvec[6]))))
		imagvalue := (1 - 2*bitvec[1]) * (8 - (1-2*bitvec[3])*(4-(1-2*bitvec[2]+5)*(2-(1-2*bitvec[7]))))
		fmt.Printf("%f+j%f", realvalue, imagvalue)
		// symbol := complex(float64(realvalue), float64(imagvalue))

	}
	// var i float64 = 0
	var length int = int(math.Exp2(float64(m.bitsPerSymbol)))
	m.size = length
	m.Constellation = make([]complex128, length)
	m.constellationTable = make(map[string]complex128, length)
	m.keys = make([]string, length)
	m.keys = sources.GrayCode(length)

	for i := 0; i < (len(m.Constellation)); i++ {
		var angle = float64(length-i) * 2 * math.Pi / float64(length)
		value := complex(math.Cos(angle+m.offset), math.Sin(angle+m.offset))
		m.Constellation[int(i)] = value
		// key := strconv.FormatInt(int64(i), 2)
		// if len(key) < m.bitsPerSymbol {
		// key = "0" + key
		// }
		key := m.keys[i]
		m.constellationTable[key] = value
		// fmt.Print("\n Init ", key, value, m.constellationTable[key])

		// m.keys[i] = key
	}

}
Example #29
0
func Exp2(f float64) float64 {
	f2 := (f + exp2Offset) * exp2Factor
	i := int(f2)
	if i < 0 || i >= exp2Len-1 {
		return math.Exp2(f)
	}
	d := f2 - math.Trunc(f2)
	return exp2[i]*(1-d) + exp2[i+1]*d
}
Example #30
0
// Split blocks. Typically block size will be maxSize / 4
// Minimum block size is maxSize/64.
//
// The break point is content dependent.
// Any insertions, deletions, or edits that occur before the start of the 32+ byte dependency window
// don't affect the break point.
// This makes it likely for two files to still have identical fragments far away from any edits.
func newZpaqWriter(maxSize uint) *zpaqWriter {
	fragment := math.Log2(float64(maxSize) / (64 * 64))
	mh := math.Exp2(22 - fragment)
	return &zpaqWriter{
		maxFragment: int(maxSize),
		minFragment: int(maxSize / 64),
		maxHash:     uint32(mh),
	}
}