Is there a standard type in Go that can do 'exact division'?

WBOY
Release: 2024-02-13 22:15:11
forward
401 people have browsed it

Go 中是否有一个标准类型可以进行“精确除法”?

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.

Question content

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
}
Copy after login

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}
}
Copy after login

But there may be a more elegant way to do this, or a "standard type" that already does this.

Solution

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template