Arithmetic Operations with Floating-Point Numbers
Now that we have a basic understanding of floating-point numbers in Go, let's explore the various arithmetic operations that can be performed with them.
Go supports the standard arithmetic operations of addition (+
), subtraction (-
), multiplication (*
), and division (/
) for both float32
and float64
data types. These operations follow the IEEE 754 standard for floating-point arithmetic, ensuring consistent and predictable behavior across different platforms and implementations.
Here's an example demonstrating these arithmetic operations:
package main
import "fmt"
func main() {
// Addition
a := 3.14
b := 2.71
sum := a + b
fmt.Println("Addition:", sum) // Output: Addition: 5.85
// Subtraction
difference := a - b
fmt.Println("Subtraction:", difference) // Output: Subtraction: 0.43
// Multiplication
product := a * b
fmt.Println("Multiplication:", product) // Output: Multiplication: 8.5094
// Division
quotient := a / b
fmt.Println("Division:", quotient) // Output: Division: 1.1583
}
In this example, we perform various arithmetic operations on float64
values and print the results. The output demonstrates the expected behavior of these operations.
It's important to note that while floating-point arithmetic is generally reliable, there can be some precision and rounding issues due to the way floating-point numbers are represented in binary. In the next section, we'll explore these limitations in more detail.