Programming Language: Golang

Namespace/Package Name: math/big

Class/Type: Rat

Method/Function: Add

Examples at hotexamples.com: 30

The math/big package in Go provides arbitrary-precision arithmetic on integers and floats. The Rat type is a rational number type with a numerator and denominator represented as big.Int values.

The Add method in the Rat type adds the given Rat value to the current value of the receiver and returns the result. Here are some examples:

**Example 1:** Add two Rat values

In this example, we create two Rat values representing 1/2 and 3/4, then add them together using the Add method. The result should be 1.25 which is outputted using the FloatString method.

**Example 2:** Add a Rat value and an int value

The Add method in the Rat type adds the given Rat value to the current value of the receiver and returns the result. Here are some examples:

package main import ( "fmt" "math/big" ) func main() { r1 := big.NewRat(1, 2) // 1/2 r2 := big.NewRat(3, 4) // 3/4 r1.Add(r1, r2) // add r2 to r1 fmt.Println(r1.FloatString(2)) // output: 1.25 }

In this example, we create two Rat values representing 1/2 and 3/4, then add them together using the Add method. The result should be 1.25 which is outputted using the FloatString method.

package main import ( "fmt" "math/big" ) func main() { r := big.NewRat(2, 7) // 2/7 i := 5 r.Add(r, big.NewRat(int64(i), 1)) // add i to r fmt.Println(r.FloatString(2)) // output: 2.71 }In this example, we create a Rat value representing 2/7 and an int value of 5, then add the int value to the Rat value using the Add method. The result should be 2.71 which is outputted using the FloatString method. Package library: math/big

Frequently Used Methods

Frequently Used Methods

Frequently Used Methods

Related

Related in langs