Home > Article > Backend Development > Is there a standard type in Go that can do "exact division"?
Is there a standard type in Go that can do "exact division"? This is a common question, let’s answer it. In Go, there is no standard type that can perform "exact division" because the integer types in Go are fixed-precision and cannot represent infinite-precision decimals. However, Go provides a solution by using floating point types for division operations. Floating-point number types in Go include float32 and float64, which can represent a larger range of numbers, but due to the characteristics of floating-point numbers, there may be a loss of precision. Therefore, if exact division is required, it is recommended to use a large number library (such as the math/big package) to handle it. This ensures accurate results when performing division operations.
I want to do some "exact division" in go. Are there standard types?
For example, I want to store the values "1/3" and "2/3" and be able to add them.
I can define my own type like this:
type mytype struct { numerator int denominator int }
And define the following functions:
func (a MyType) Plus(b MyType) MyType { d := a.Denominator * b.Denominator n := (a.Numerator * b.Denominator) + (b.Numerator * a.Denominator) return MyType{Numerator: n, Denominator: d} }
But there may be a more elegant way to do this, or a "standard type" that already does this.
I don’t know big.Rat
. That's all I need! thank you for your help
The above is the detailed content of Is there a standard type in Go that can do "exact division"?. For more information, please follow other related articles on the PHP Chinese website!