// DecimalDiv does division of two decimals.
//
// from1    - dividend
// from2    - divisor
// to       - quotient
// fracIncr - increment of fraction
519822
func DecimalDiv(from1, from2, to *MyDecimal, fracIncr int) error {
	to.resultFrac = myMinInt8(from1.resultFrac+int8(fracIncr), MaxFraction)
	return doDivMod(from1, from2, to, nil, fracIncr)
}
598058
func DivFloatRegReg(ctx context, datatype OpDataType, dividend, divisor *register, spill bool) string {
	if dividend.width != divisor.width {
		ice("Invalid register width")
	}
	if datatype.op != OP_XMM {
		ice("Unsupported data type for floating point division")
	}
	return instrRegReg(ctx, GetInstr(I_DIV, datatype), divisor, dividend, true)
}
1129770
func formatPct(f float64, div float64) float64 {
	// avoid division by 0
	if div == 0 {
		div = 1
	}
	rounded := math.Floor((f / div * 10000) + .5)
	return math.Max(rounded/100, 0)
}
1330618
func (accounting *Accounting) FormatMoneyBigDecimal(value *apd.Decimal) string {
	if !accounting.isInitialized {
		accounting.init()
	}
	formattedNumber := FormatNumberBigDecimal(value, accounting.Precision, accounting.Thousand, accounting.Decimal)
	return accounting.formatMoneyString(formattedNumber)
}
2221
func ComputeIntDiv(sc *variable.StatementContext, a, b Datum) (d Datum, err error) {
	switch a.Kind() {
	case KindInt64:
		x := a.GetInt64()
		switch b.Kind() {
		case KindInt64:
			y := b.GetInt64()
			if y == 0 {
				return d, nil
			}
			r, err1 := DivInt64(x, y)
			d.SetInt64(r)
			return d, errors.Trace(err1)
		case KindUint64:
			y := b.GetUint64()
			if y == 0 {
				return d, nil
			}
			r, err1 := DivIntWithUint(x, y)
			d.SetUint64(r)
			return d, errors.Trace(err1)
		}
	case KindUint64:
		x := a.GetUint64()
		switch b.Kind() {
		case KindInt64:
			y := b.GetInt64()
			if y == 0 {
				return d, nil
			}
			r, err1 := DivUintWithInt(x, y)
			d.SetUint64(r)
			return d, errors.Trace(err1)
		case KindUint64:
			y := b.GetUint64()
			if y == 0 {
				return d, nil
			}
			d.SetUint64(x / y)
			return d, nil
		}
	}

	// If either is not integer, use decimal to calculate
	x, err := a.ToDecimal(sc)
	if err != nil {
		return d, errors.Trace(err)
	}

	y, err := b.ToDecimal(sc)
	if err != nil {
		return d, errors.Trace(err)
	}
	to := new(MyDecimal)
	err = DecimalDiv(x, y, to, DivFracIncr)
	if err == ErrDivByZero {
		return d, nil
	}
	iVal, err1 := to.ToInt()
	if err == nil {
		err = err1
	}
	d.SetInt64(iVal)
	return d, nil
}
61724
func doublePercent(str string) string {
	if strings.Contains(str, "%") {
		str = strings.Replace(str, "%", "%%", -1)
	}
	return str
}
525344
func Div(a, b []float64) {
	b = b[:len(a)]
	for i, v := range a {
		if b[i] == 0 {
			a[i] = math.Inf(0)
			continue
		}

		a[i] = v / b[i]
	}
}
373183
func (a *AggregateSample) Stddev() float64 {
	num := (float64(a.Count) * a.SumSq) - math.Pow(a.Sum, 2)
	div := float64(a.Count * (a.Count - 1))
	if div == 0 {
		return 0
	}
	return math.Sqrt(num / div)
}
1004444
func (f *extFloat) FixedDecimal(d *decimalSlice, n int) bool {
	if f.mant == 0 {
		d.nd = 0
		d.dp = 0
		d.neg = f.neg
		return true
	}
	if n == 0 {
		panic("strconv: internal error: extFloat.FixedDecimal called with n == 0")
	}
	// Multiply by an appropriate power of ten to have a reasonable
	// number to process.
	f.Normalize()
	exp10, _ := f.frexp10()

	shift := uint(-f.exp)
	integer := uint32(f.mant >> shift)
	fraction := f.mant - (uint64(integer) << shift)
	ε := uint64(1) // ε is the uncertainty we have on the mantissa of f.

	// Write exactly n digits to d.
	needed := n        // how many digits are left to write.
	integerDigits := 0 // the number of decimal digits of integer.
	pow10 := uint64(1) // the power of ten by which f was scaled.
	for i, pow := 0, uint64(1); i < 20; i++ {
		if pow > uint64(integer) {
			integerDigits = i
			break
		}
		pow *= 10
	}
	rest := integer
	if integerDigits > needed {
		// the integral part is already large, trim the last digits.
		pow10 = uint64pow10[integerDigits-needed]
		integer /= uint32(pow10)
		rest -= integer * uint32(pow10)
	} else {
		rest = 0
	}

	// Write the digits of integer: the digits of rest are omitted.
	var buf [32]byte
	pos := len(buf)
	for v := integer; v > 0; {
		v1 := v / 10
		v -= 10 * v1
		pos--
		buf[pos] = byte(v + '0')
		v = v1
	}
	for i := pos; i < len(buf); i++ {
		d.d[i-pos] = buf[i]
	}
	nd := len(buf) - pos
	d.nd = nd
	d.dp = integerDigits + exp10
	needed -= nd

	if needed > 0 {
		if rest != 0 || pow10 != 1 {
			panic("strconv: internal error, rest != 0 but needed > 0")
		}
		// Emit digits for the fractional part. Each time, 10*fraction
		// fits in a uint64 without overflow.
		for needed > 0 {
			fraction *= 10
			ε *= 10 // the uncertainty scales as we multiply by ten.
			if 2*ε > 1<<shift {
				// the error is so large it could modify which digit to write, abort.
				return false
			}
			digit := fraction >> shift
			d.d[nd] = byte(digit + '0')
			fraction -= digit << shift
			nd++
			needed--
		}
		d.nd = nd
	}

	// We have written a truncation of f (a numerator / 10^d.dp). The remaining part
	// can be interpreted as a small number (< 1) to be added to the last digit of the
	// numerator.
	//
	// If rest > 0, the amount is:
	//    (rest<<shift | fraction) / (pow10 << shift)
	//    fraction being known with a ±ε uncertainty.
	//    The fact that n > 0 guarantees that pow10 << shift does not overflow a uint64.
	//
	// If rest = 0, pow10 == 1 and the amount is
	//    fraction / (1 << shift)
	//    fraction being known with a ±ε uncertainty.
	//
	// We pass this information to the rounding routine for adjustment.

	ok := adjustLastDigitFixed(d, uint64(rest)<<shift|fraction, pow10, shift, ε)
	if !ok {
		return false
	}
	// Trim trailing zeros.
	for i := d.nd - 1; i >= 0; i-- {
		if d.d[i] != '0' {
			d.nd = i + 1
			break
		}
	}
	return true
}
305754
func (m *FractionalPercent) Validate() error {
	if m == nil {
		return nil
	}

	// no validation rules for Numerator

	if _, ok := FractionalPercent_DenominatorType_name[int32(m.GetDenominator())]; !ok {
		return FractionalPercentValidationError{
			field:  "Denominator",
			reason: "value must be one of the defined enum values",
		}
	}

	return nil
}
778158
func (x Pol) DivMod(d Pol) (Pol, Pol) {
	if x == 0 {
		return 0, 0
	}

	if d == 0 {
		panic("division by zero")
	}

	D := d.Deg()
	diff := x.Deg() - D
	if diff < 0 {
		return 0, x
	}

	var q Pol
	for diff >= 0 {
		m := d << uint(diff)
		q |= (1 << uint(diff))
		x = x.Add(m)

		diff = x.Deg() - D
	}

	return q, x
}
616877
func (d *Decimal) Value() (driver.Value, error) {
	if d.V == nil {
		if d.Zero {
			return "0", nil
		}
		return nil, nil
	}
	v := d.V
	if v.IsNaN(0) {
		return "NaN", nil
	}
	if v.IsInf(0) {
		return nil, errors.New("Decimal.Value: DECIMAL does not accept Infinities")
	}

	dl := v.Precision()  // length of d
	sl := int(v.Scale()) // length of fractional part

	if il := dl - sl; il > MaxIntegralDigits {
		if !d.Round {
			return nil, &LengthError{Part: "integral", N: il, max: MaxIntegralDigits}
		}
		// Rounding down the integral part automatically chops off the fractional
		// part.
		return v.Round(MaxIntegralDigits).String(), nil
	}
	if sl > MaxFractionalDigits {
		if !d.Round {
			return nil, &LengthError{Part: "fractional", N: sl, max: MaxFractionalDigits}
		}
		v.Round(dl - (sl - MaxFractionalDigits))
	}
	return v.String(), nil
}
369129
func (m mathUtil) RoundUp(value, roundTo float64) float64 {
	if roundTo < 0.000000000000001 {
		return value
	}
	d1 := math.Ceil(value / roundTo)
	return d1 * roundTo
}
42543
func (t *Translator) formatNumber(format *numberFormat, number float64) string {
	negative := number < 0

	// apply the multiplier first - this is mainly used for percents
	value := math.Abs(number * float64(format.multiplier))
	stringValue := ""

	// get the initial string value, with the maximum # decimal digits
	if format.maxDecimalDigits >= 0 {
		stringValue = numberRound(value, format.maxDecimalDigits)
	} else {
		stringValue = fmt.Sprintf("%f", value)
	}

	// separate the integer from the decimal parts
	pos := strings.Index(stringValue, ".")
	integer := stringValue
	decimal := ""
	if pos != -1 {
		integer = stringValue[:pos]
		decimal = stringValue[pos+1:]
	}

	// make sure the minimum # decimal digits are there
	for len(decimal) < format.minDecimalDigits {
		decimal = decimal + "0"
	}

	// make sure the minimum # integer digits are there
	for len(integer) < format.minIntegerDigits {
		integer = "0" + integer
	}

	// if there's a decimal portion, prepend the decimal point symbol
	if len(decimal) > 0 {
		decimal = string(t.rules.Numbers.Symbols.Decimal) + decimal
	}

	// put the integer portion into properly sized groups
	if format.groupSizeFinal > 0 && len(integer) > format.groupSizeFinal {
		if len(integer) > format.groupSizeMain {
			groupFinal := integer[len(integer)-format.groupSizeFinal:]
			groupFirst := integer[:len(integer)-format.groupSizeFinal]
			integer = strings.Join(chunkString(groupFirst, format.groupSizeMain), t.rules.Numbers.Symbols.Group) + t.rules.Numbers.Symbols.Group + groupFinal
		}
	}

	// append/prepend negative/positive prefix/suffix
	formatted := ""
	if negative {
		formatted = format.negativePrefix + integer + decimal + format.negativeSuffix
	} else {
		formatted = format.positivePrefix + integer + decimal + format.positiveSuffix
	}

	// replace percents and permilles with the local symbols (likely to be exactly the same)
	formatted = strings.Replace(formatted, "%", string(t.rules.Numbers.Symbols.Percent), -1)
	formatted = strings.Replace(formatted, "‰", string(t.rules.Numbers.Symbols.Permille), -1)

	return formatted
}
1110181
func someDigits(buf *bytes.Buffer, d int64) {
	// Print into the top, then copy down.
	tmp := make([]byte, 10)
	j := 10
	for {
		j--
		tmp[j] = digits[d%10]
		d /= 10
		if d == 0 {
			break
		}
	}
	buf.Write(tmp[j:])
}
989259
func (ns *Namespace) Div(a, b interface{}) (interface{}, error) {
	return _math.DoArithmetic(a, b, '/')
}
776207
func (a *AggFuncDesc) Split(ordinal []int) (partialAggDesc, finalAggDesc *AggFuncDesc) {
	partialAggDesc = a.Clone()
	if a.Mode == CompleteMode {
		partialAggDesc.Mode = Partial1Mode
	} else if a.Mode == FinalMode {
		partialAggDesc.Mode = Partial2Mode
	} else {
		panic("Error happened during AggFuncDesc.Split, the AggFunctionMode is not CompleteMode or FinalMode.")
	}
	finalAggDesc = &AggFuncDesc{
		Mode:        FinalMode, // We only support FinalMode now in final phase.
		HasDistinct: a.HasDistinct,
	}
	finalAggDesc.Name = a.Name
	finalAggDesc.RetTp = a.RetTp
	switch a.Name {
	case ast.AggFuncAvg:
		args := make([]expression.Expression, 0, 2)
		args = append(args, &expression.Column{
			ColName: model.NewCIStr(fmt.Sprintf("avg_final_col_%d", ordinal[0])),
			Index:   ordinal[0],
			RetType: types.NewFieldType(mysql.TypeLonglong),
		})
		args = append(args, &expression.Column{
			ColName: model.NewCIStr(fmt.Sprintf("avg_final_col_%d", ordinal[1])),
			Index:   ordinal[1],
			RetType: a.RetTp,
		})
		finalAggDesc.Args = args
	default:
		args := make([]expression.Expression, 0, 1)
		args = append(args, &expression.Column{
			ColName: model.NewCIStr(fmt.Sprintf("%s_final_col_%d", a.Name, ordinal[0])),
			Index:   ordinal[0],
			RetType: a.RetTp,
		})
		finalAggDesc.Args = args
		if finalAggDesc.Name == ast.AggFuncGroupConcat {
			finalAggDesc.Args = append(finalAggDesc.Args, a.Args[len(a.Args)-1]) // separator
		}
	}
	return
}