Arithmetic Operations
Basic Floating-Point Arithmetic
Floating-point arithmetic in Go involves standard mathematical operations with decimal numbers. Understanding these operations is crucial for numerical computations.
Standard Arithmetic Operators
package main
import (
"fmt"
"math"
)
func main() {
// Addition
a := 10.5
b := 3.2
sum := a + b
fmt.Printf("Addition: %.2f + %.2f = %.2f\n", a, b, sum)
// Subtraction
difference := a - b
fmt.Printf("Subtraction: %.2f - %.2f = %.2f\n", a, b, difference)
// Multiplication
product := a * b
fmt.Printf("Multiplication: %.2f * %.2f = %.2f\n", a, b, product)
// Division
quotient := a / b
fmt.Printf("Division: %.2f / %.2f = %.2f\n", a, b, quotient)
}
Advanced Mathematical Functions
Go's math
package provides extensive floating-point operations:
func main() {
x := 16.0
// Square root
sqrt := math.Sqrt(x)
fmt.Printf("Square Root: √%.2f = %.2f\n", x, sqrt)
// Power
power := math.Pow(x, 2)
fmt.Printf("Power: %.2f² = %.2f\n", x, power)
// Trigonometric functions
angle := math.Pi / 4
sine := math.Sin(angle)
cosine := math.Cos(angle)
fmt.Printf("Sine of π/4: %.2f\n", sine)
fmt.Printf("Cosine of π/4: %.2f\n", cosine)
}
Comparison Operations
func main() {
a := 10.5
b := 3.2
// Comparison operators
fmt.Printf("a > b: %v\n", a > b)
fmt.Printf("a < b: %v\n", a < b)
fmt.Printf("a == b: %v\n", a == b)
fmt.Printf("a >= b: %v\n", a >= b)
}
Floating-Point Precision Challenges
graph TD
A[Floating-Point Arithmetic] --> B[Precision Limitations]
B --> C[Binary Representation]
B --> D[Rounding Errors]
B --> E[Comparison Challenges]
Handling Precision Considerations
Operation |
Potential Issue |
Recommendation |
Equality Comparison |
Exact match rarely works |
Use math.Abs(a-b) < epsilon |
Large Calculations |
Accumulation of errors |
Use specialized libraries |
Financial Calculations |
Precision critical |
Consider decimal libraries |
Special Floating-Point Values
func main() {
// Special values
positiveInf := math.Inf(1)
negativeInf := math.Inf(-1)
notANumber := math.NaN()
fmt.Printf("Positive Infinity: %v\n", positiveInf)
fmt.Printf("Negative Infinity: %v\n", negativeInf)
fmt.Printf("Not a Number: %v\n", notANumber)
}
Best Practices
- Use
float64
for most calculations
- Be cautious with direct floating-point comparisons
- Understand potential precision limitations
- Utilize math package functions for complex operations
Conclusion
Mastering floating-point arithmetic requires understanding both mathematical principles and computational limitations. LabEx recommends continuous practice and careful consideration of precision in numerical computations.