github.com/loov/hrtime@v1.0.3/histogram_bounds.go (about)

     1  package hrtime
     2  
     3  import "math"
     4  
     5  func calculateSteps(min, max float64, bincount int) (minimum, spacing float64) {
     6  	minimum = min
     7  	spacing = (max - min) / float64(bincount)
     8  	return minimum, spacing
     9  }
    10  
    11  func calculateNiceSteps(min, max float64, bincount int) (minimum, spacing float64) {
    12  	span := niceNumber(max-min, false)
    13  	spacing = niceNumber(span/float64(bincount-1), true)
    14  	minimum = math.Floor(min/spacing) * spacing
    15  	return minimum, spacing
    16  }
    17  
    18  func niceNumber(span float64, round bool) float64 {
    19  	exp := math.Floor(math.Log10(span))
    20  	frac := span / math.Pow(10, exp)
    21  
    22  	var nice float64
    23  	if round {
    24  		switch {
    25  		case frac < 1.5:
    26  			nice = 1
    27  		case frac < 3:
    28  			nice = 2
    29  		case frac < 7:
    30  			nice = 5
    31  		default:
    32  			nice = 10
    33  		}
    34  	} else {
    35  		switch {
    36  		case frac <= 1:
    37  			nice = 1
    38  		case frac <= 2:
    39  			nice = 2
    40  		case frac <= 5:
    41  			nice = 5
    42  		default:
    43  			nice = 10
    44  		}
    45  	}
    46  
    47  	return nice * math.Pow(10, exp)
    48  }
    49  
    50  func truncate(v float64, digits int) float64 {
    51  	if digits == 0 || v == 0 {
    52  		return 0
    53  	}
    54  
    55  	scale := math.Pow(10, math.Floor(math.Log10(v))+1-float64(digits))
    56  	return scale * math.Trunc(v/scale)
    57  }
    58  
    59  func round(v float64, digits int) float64 {
    60  	if digits == 0 || v == 0 {
    61  		return 0
    62  	}
    63  
    64  	scale := math.Pow(10, math.Floor(math.Log10(v))+1-float64(digits))
    65  	return scale * math.Round(v/scale)
    66  }