当前位置: 首页>>代码示例>>Golang>>正文


Golang math.Log函数代码示例

本文整理汇总了Golang中math.Log函数的典型用法代码示例。如果您正苦于以下问题:Golang Log函数的具体用法?Golang Log怎么用?Golang Log使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Log函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: Classify

func (nba *Multinomial) Classify(doc string) (string, error) {
	var bestClass string
	var bestClassLogProbability float64 = -math.MaxFloat64

	for class, classPrior := range nba.classPriors {
		// Get the total class model for the point conditiond on this class
		var logSum float64 = 0
		for _, word := range words(doc) {
			logSum += math.Log(float64(nba.wordCount[class][word]+1) / float64(nba.classSize[class]+nba.vocabularySize))
		}

		// Bayes theorem: P(c|e) = (P(e|c)P(c)) / P(e)
		// We drop P(e) as it is constant
		logProbability := logSum + math.Log(classPrior)

		// Update current best class
		if logProbability > bestClassLogProbability {
			bestClassLogProbability = logProbability
			bestClass = class
		}
	}

	if bestClassLogProbability == -math.MaxFloat64 {
		return "", NoClassificationError
	}

	return bestClass, nil
}
开发者ID:postfix,项目名称:dexter,代码行数:28,代码来源:multinomial.go

示例2: MelScaleVector

// Generate a Mel Scale for sampling frequency _sampfreq_ and return a
// normalized vector of length _vectorlength_ containing equally
// spaced points between 0 and (sampfreq/2)
func MelScaleVector(sampfreq int, vectorlength int) []float64 {
	var i int
	var step float64
	var melscalevector []float64

	step = (float64(sampfreq) / 2.0) / float64(vectorlength)

	melscalevector = make([]float64, vectorlength, vectorlength)

	for i = 0; i < vectorlength; i++ {
		var melscale float64

		// Equations taken from Wikipedia
		f := step * float64(i)
		melscale = (1000.0 / math.Log(2)) * math.Log(1.0+(f/1000.0))

		melscalevector[i] = melscale
	}

	// Normalize the Vector. Values are already positive, and
	// monotonically increasing, so divide by max
	max := melscalevector[vectorlength-1]
	for i = 0; i < vectorlength; i++ {
		melscalevector[i] /= max
	}

	return melscalevector
}
开发者ID:adityanatraj,项目名称:gossp,代码行数:31,代码来源:mcep_alpha_calc.go

示例3: Classify

func (nba *Gaussian) Classify(point Point) (string, error) {
	if len(point) != nba.dimensionality {
		return "", WrongDimensionError
	}

	var bestClass string
	var bestClassLogProbability float64 = -math.MaxFloat64

	for class, classPrior := range nba.classPriors {

		// Get the total class model for the point conditiond on this class
		var logSum float64 = 0
		for i, prior := range nba.classModel[class] {
			logSum += math.Log(prior.Likelihood(point[i]))
		}

		// Bayes theorem: P(c|e) = (P(e|c)P(c)) / P(e)
		// We drop P(e) as it is constant
		logProbability := logSum + math.Log(classPrior)

		// Update current best class
		if logProbability > bestClassLogProbability {
			bestClassLogProbability = logProbability
			bestClass = class
		}
	}

	if bestClassLogProbability == -math.MaxFloat64 {
		return "", NoClassificationError
	}

	return bestClass, nil
}
开发者ID:postfix,项目名称:dexter,代码行数:33,代码来源:gaussian.go

示例4: estimates64

func estimates64(n uint64, p float64) (uint64, uint64) {
	nf := float64(n)
	log2 := math.Log(2)
	m := -1 * nf * math.Log(p) / math.Pow(log2, 2)
	k := math.Ceil(log2 * m / nf)
	return uint64(m), uint64(k)
}
开发者ID:patrickmn,项目名称:go-bloom,代码行数:7,代码来源:bloom64.go

示例5: LogarithmicRegression

// LogarithmicRegression returns an logarithmic regression on data series
func LogarithmicRegression(s Series) (regressions Series, err error) {

	if len(s) == 0 {
		return nil, errors.New("Input must not be empty")
	}

	var sum [4]float64

	i := 0
	for ; i < len(s); i++ {
		sum[0] += math.Log(s[i].X)
		sum[1] += s[i].Y * math.Log(s[i].X)
		sum[2] += s[i].Y
		sum[3] += math.Pow(math.Log(s[i].X), 2)
	}

	f := float64(i)
	a := (f*sum[1] - sum[2]*sum[0]) / (f*sum[3] - sum[0]*sum[0])
	b := (sum[2] - a*sum[0]) / f

	for j := 0; j < len(s); j++ {
		regressions = append(regressions, Coordinate{
			X: s[j].X,
			Y: b + a*math.Log(s[j].X),
		})
	}

	return regressions, nil

}
开发者ID:nsajko,项目名称:stats,代码行数:31,代码来源:stats.go

示例6: scalarMercatorProject

func scalarMercatorProject(lng, lat float64, level uint64) (x, y uint64) {
	var factor uint64

	factor = 1 << level
	maxtiles := float64(factor)

	lng = lng/360.0 + 0.5
	x = uint64(lng * maxtiles)

	// bound it because we have a top of the world problem
	siny := math.Sin(lat * math.Pi / 180.0)

	if siny < -0.9999 {
		lat = 0.5 + 0.5*math.Log((1.0+siny)/(1.0-siny))/(-2*math.Pi)
		y = 0
	} else if siny > 0.9999 {
		lat = 0.5 + 0.5*math.Log((1.0+siny)/(1.0-siny))/(-2*math.Pi)
		y = factor - 1
	} else {
		lat = 0.5 + 0.5*math.Log((1.0+siny)/(1.0-siny))/(-2*math.Pi)
		y = uint64(lat * maxtiles)
	}

	return
}
开发者ID:thomaspeugeot,项目名称:go.geo,代码行数:25,代码来源:projections.go

示例7: NormFloat64

// NormFloat64 returns a normally distributed float64 in the range
// [-math.MaxFloat64, +math.MaxFloat64] with
// standard normal distribution (mean = 0, stddev = 1).
// To produce a different normal distribution, callers can
// adjust the output using:
//
//  sample = NormFloat64() * desiredStdDev + desiredMean
//
func (r *Rand) NormFloat64() float64 {
	for {
		j := int32(r.Uint32()) // Possibly negative
		i := j & 0x7F
		x := float64(j) * float64(wn[i])
		if absInt32(j) < kn[i] {
			// This case should be hit better than 99% of the time.
			return x
		}

		if i == 0 {
			// This extra work is only required for the base strip.
			for {
				x = -math.Log(r.Float64()) * (1.0 / rn)
				y := -math.Log(r.Float64())
				if y+y >= x*x {
					break
				}
			}
			if j > 0 {
				return rn + x
			}
			return -rn - x
		}
		if fn[i]+float32(r.Float64())*(fn[i-1]-fn[i]) < float32(math.Exp(-.5*x*x)) {
			return x
		}
	}
}
开发者ID:2thetop,项目名称:go,代码行数:37,代码来源:normal.go

示例8: HarmonicMean

// HarmonicMean returns the weighted harmonic mean of the dataset
//  \sum_i {w_i} / ( sum_i {w_i / x_i} )
// This only applies with positive x and positive weights.
// If weights is nil then all of the weights are 1. If weights is not nil, then
// len(x) must equal len(weights).
func HarmonicMean(x, weights []float64) float64 {
	if weights != nil && len(x) != len(weights) {
		panic("stat: slice length mismatch")
	}
	// TODO: Fix this to make it more efficient and avoid allocation

	// This can be numerically unstable (for example if x is very small)
	// W = \sum_i {w_i}
	// hm = exp(log(W) - log(\sum_i w_i / x_i))

	logs := make([]float64, len(x))
	var W float64
	for i := range x {
		if weights == nil {
			logs[i] = -math.Log(x[i])
			W++
			continue
		}
		logs[i] = math.Log(weights[i]) - math.Log(x[i])
		W += weights[i]
	}

	// Sum all of the logs
	v := floats.LogSumExp(logs) // this computes log(\sum_i { w_i / x_i})
	return math.Exp(math.Log(W) - v)
}
开发者ID:darrenmcc,项目名称:stat,代码行数:31,代码来源:stat.go

示例9: Grad

func (GulfResearchAndDevelopment) Grad(grad, x []float64) {
	if len(x) != 3 {
		panic("dimension of the problem must be 3")
	}
	if len(x) != len(grad) {
		panic("incorrect size of the gradient")
	}

	for i := range grad {
		grad[i] = 0
	}
	for i := 1; i <= 99; i++ {
		arg := float64(i) / 100
		r := math.Pow(-50*math.Log(arg), 2.0/3.0) + 25 - x[1]
		t1 := math.Pow(math.Abs(r), x[2]) / x[0]
		t2 := math.Exp(-t1)
		t := t2 - arg
		s1 := t1 * t2 * t
		grad[0] += s1
		grad[1] += s1 / r
		grad[2] -= s1 * math.Log(math.Abs(r))
	}
	grad[0] *= 2 / x[0]
	grad[1] *= 2 * x[2]
	grad[2] *= 2
}
开发者ID:jgcarvalho,项目名称:zdd,代码行数:26,代码来源:functions.go

示例10: TestLogSquared

func TestLogSquared(t *testing.T) {
	prediction := []float64{1, -2, 3}
	truth := []float64{1.1, -2.2, 2.7}
	trueloss := (math.Log(.1*.1+1) + math.Log(.2*.2+1) + math.Log(.3*.3+1)) / 3
	derivative := []float64{0, 0, 0}

	sq := LogSquared{}
	loss := sq.Loss(prediction, truth)
	if math.Abs(loss-trueloss) > TOL {
		t.Errorf("loss doesn't match from Loss(). Expected %v, Found: %v", trueloss, loss)
	}

	loss = sq.LossDeriv(prediction, truth, derivative)
	if math.Abs(loss-trueloss) > TOL {
		t.Errorf("loss doesn't match from LossDeriv()")
	}
	derivative, fdDerivative := finiteDifferenceLosser(sq, prediction, truth)
	if !floats.EqualApprox(derivative, fdDerivative, FDTol) {
		t.Errorf("Derivative doesn't match. \n deriv: %v \n fdDeriv: %v ", derivative, fdDerivative)
	}
	err := common.InterfaceTestMarshalAndUnmarshal(sq)
	if err != nil {
		t.Errorf("Error marshaling and unmarshaling")
	}
}
开发者ID:reggo,项目名称:reggo,代码行数:25,代码来源:loss_test.go

示例11: Primes

// Primes is using Segmented sieve. This method will reduce memory usae of Sieve of Eratosthenes considerably.
// besides memory allocation for Prime numbers slice, there is only O(sqrt(n)) extra memory required for the operation
// You can learn more about it in https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes.
func Primes(n uint64) (allPrimes []uint64) {
	if uint64(math.Log(float64(n))-1) == 0 {
		return SieveOfEratosthenes(n)
	}

	// There is a function pi(x) in math that will returns approximate number of prime numbers below n.
	allPrimes = make([]uint64, 0, n/uint64(math.Log(float64(n))-1))
	segSize := uint64(math.Sqrt(float64(n)))

	csegPool.New = func() interface{} {
		return make([]bool, segSize)
	}

	basePrimes := SieveOfEratosthenes(segSize)
	allPrimes = append(allPrimes, basePrimes...)

	cores := runtime.NumCPU()
	next := make(chan bool, cores)
	var nextTurn []chan bool
	nextTurn = make([]chan bool, n/segSize+1)
	for i := uint64(0); i < n/segSize+1; i++ {
		nextTurn[i] = make(chan bool)
	}
	for segNum := uint64(1); segNum <= n/segSize; segNum++ {
		go fillSegments(n, basePrimes, &allPrimes, segSize, segNum, next, nextTurn)
		next <- true
	}
	for i := 0; i < cores; i++ {
		next <- true
	}

	return allPrimes
}
开发者ID:kavehmz,项目名称:prime,代码行数:36,代码来源:prime.go

示例12: Predict

// Predict takes in a document, predicts the
// class of the document based on the training
// data passed so far, and returns the class
// estimated for the document.
func (b *NaiveBayes) Predict(sentence string) uint8 {
	sums := make([]float64, len(b.Count))

	sentence, _, _ = transform.String(b.sanitize, sentence)
	words := b.Tokenizer.Tokenize(sentence)
	for _, word := range words {
		w, ok := b.Words.Get(word)
		if !ok {
			continue
		}

		for i := range sums {
			sums[i] += math.Log(float64(w.Count[i]+1) / float64(w.Seen+b.DictCount))
		}
	}

	for i := range sums {
		sums[i] += math.Log(b.Probabilities[i])
	}

	// find best class
	var maxI int
	for i := range sums {
		if sums[i] > sums[maxI] {
			maxI = i
		}
	}

	return uint8(maxI)
}
开发者ID:cdipaolo,项目名称:goml,代码行数:34,代码来源:bayes.go

示例13: Predict

// Predict takes in a document, predicts the
// class of the document based on the training
// data passed so far, and returns the class
// estimated for the document.
func (b *NaiveBayes) Predict(sentence string) uint8 {
	sums := make([]float64, len(b.Count))

	sentence, _, _ = transform.String(b.sanitize, sentence)
	w := strings.Split(strings.ToLower(sentence), " ")
	for _, word := range w {
		if _, ok := b.Words[word]; !ok {
			continue
		}

		for i := range sums {
			sums[i] += math.Log(float64(b.Words[word].Count[i]+1) / float64(b.Words[word].Seen+b.DictCount))
		}
	}

	for i := range sums {
		sums[i] += math.Log(b.Probabilities[i])
	}

	// find best class
	var maxI int
	for i := range sums {
		if sums[i] > sums[maxI] {
			maxI = i
		}
	}

	return uint8(maxI)
}
开发者ID:livitski,项目名称:goml,代码行数:33,代码来源:bayes.go

示例14: mandelbrotColor

// mandelbrotColor computes a Mandelbrot value and then assigns a color from the
// color table.
func mandelbrotColor(c complex128, zoom int) color.RGBA {
	// Scale so we can fit the entire set in one tile when zoomed out.
	c = c*3.5 - complex(2.5, 1.75)

	z := complex(0, 0)
	iter := 0
	for ; iter < iterations; iter++ {
		z = z*z + c
		r, i := real(z), imag(z)
		absSquared := r*r + i*i
		if absSquared >= 4 {
			// This is the "Continuous (smooth) coloring" described in Wikipedia:
			// http://en.wikipedia.org/wiki/Mandelbrot_set#Continuous_.28smooth.29_coloring
			v := float64(iter) - math.Log2(math.Log(cmplx.Abs(z))/math.Log(4))

			// We are scaling the value based on the zoom level so things don't get
			// too busy as we get further in.
			v = math.Abs(v) * float64(colorDensity) / math.Max(float64(zoom), 1)
			minValue = math.Min(float64(v), minValue)
			maxValue = math.Max(float64(v), maxValue)
			colorIdx := (int(v) + numColors*zoom/len(colorStops)) % numColors
			return colors[colorIdx]
		}
	}

	return centerColor
}
开发者ID:jonparrott,项目名称:compute-appengine-demo-suite-python,代码行数:29,代码来源:mandelbrot.go

示例15: startBenchmarkClient

func startBenchmarkClient(config *testpb.ClientConfig) (*benchmarkClient, error) {
	printClientConfig(config)

	// Set running environment like how many cores to use.
	setupClientEnv(config)

	conns, closeConns, err := createConns(config)
	if err != nil {
		return nil, err
	}

	rpcCountPerConn := int(config.OutstandingRpcsPerChannel)
	bc := &benchmarkClient{
		histogramOptions: stats.HistogramOptions{
			NumBuckets:     int(math.Log(config.HistogramParams.MaxPossible)/math.Log(1+config.HistogramParams.Resolution)) + 1,
			GrowthFactor:   config.HistogramParams.Resolution,
			BaseBucketSize: (1 + config.HistogramParams.Resolution),
			MinValue:       0,
		},
		lockingHistograms: make([]lockingHistogram, rpcCountPerConn*len(conns), rpcCountPerConn*len(conns)),

		stop:          make(chan bool),
		lastResetTime: time.Now(),
		closeConns:    closeConns,
	}

	if err = performRPCs(config, conns, bc); err != nil {
		// Close all connections if performRPCs failed.
		closeConns()
		return nil, err
	}

	return bc, nil
}
开发者ID:ruinanchen,项目名称:grpc-go,代码行数:34,代码来源:benchmark_client.go


注:本文中的math.Log函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。