Go: Float Types

Go: Float Types

Describe float type in Go language.

ยท

6 min read

In Go, float types are used to represent fractional numbers with floating-point precision. There are two kinds of floating point types in Go: float32 and float64, which respectively have 32 and 64 bits in memory.

Here's an example of using a floating point literal in Go:

var myFloat float64 = 3.14159

Go also provides a shorthand for initializing floating point literals using scientific notation. For example:

var myOtherFloat = 1.0e+10

This initializes a variable of type float64 with the value of 1 with 10 zeros following, which is equivalent to 1,000,000,000.


Conversion

When it comes to conversion, Go provides a built-in package called strconv that developers can use to convert floating point numbers to and from their string representation. Here's an example:

import "strconv"

func main() {
    // Convert float64 to string
    myFloat := 3.1415
    // 2 decimal places
    myString := strconv.FormatFloat(myFloat, 'f', 2, 64)

    fmt.Println(myString)

    // Convert string to float64
    myNewString := "1.234"
    myNewFloat, err := strconv.ParseFloat(myNewString, 64)

    fmt.Println(myNewFloat, err)
}

In addition to converting float types, Go also provides several options for converting integer types to and from float types. Here are some examples:

var myInt int = 42
 // Convert integer to float
var myFloat = float64(myInt)

var myOtherFloat = 3.14
// Convert float to integer
var myInt = int(myOtherFloat)

These conversions may result in some data loss or rounding errors, so it is important for developers to understand their specific use cases before converting one type to another.


Operators

In Go, there are several operators that can be used to produce float numbers:

  1. / operator: When dividing two integer values, the result will be a float if either operand is a float.
result := 5 / 2 // Result is 2, because we are dividing two integers

result = 5.0 / 2 // Result is 2.5, because we are dividing a float by an integer
  1. math package functions: The math package in Go provides several functions that return float numbers, such as Sqrt, Sin, Cos, Log, and more.
result := math.Sqrt(4) // Result is 2.0, because the square root of 4 is 2
  1. Combining integers and floats in expressions: When an expression includes both integers and floats, Go will perform automatic type conversion to produce a float result.
result := 5 + 2.5 // Result is 7.5, because we are adding an integer and a float

Integers & Floats

Here are some example expressions that combine integers and floats to produce float results:

var myFloat float64 = 3.14
var myInt int = 2

var result1 = myFloat / float64(myInt) // Result is 1.57, because we are dividing a float by an integer
var result2 = float64(myInt) + myFloat // Result is 5.14, because we are adding an integer and a float

In these examples, Go will automatically convert the integer value to a float to perform the division and addition operations.


Avoiding Errors

In Go, there are several types of errors that can occur when working with float expressions. Here are some common errors and how to prevent them using smart code assertions:

  1. Division by zero: When dividing a number by zero, Go will return inf or NaN. To prevent this, you can use a conditional statement to check if the divisor is zero before performing the division.
dividend := 10.0
divisor := 0.0

if divisor != 0 {
    quotient := dividend / divisor
    fmt.Println(quotient)
} else {
    fmt.Println("Error: division by zero")
}
  1. Comparison of two float values: Due to the way that float values are represented in memory, comparing two floats for equality can sometimes produce unexpected results. To prevent this, you can use a tolerance value and check if the absolute difference between the two floats is less than the tolerance.
func equals(x, y, tolerance float64) bool {
    return math.Abs(x-y) < tolerance
}

result := 0.1 + 0.2 // Result is 0.30000000000000004, not exactly 0.3

if equals(result, 0.3, 0.0001) {
    fmt.Println("The two values are roughly equal")
} else {
    fmt.Println("The two values are different")
}
  1. Overflow and underflow: When a float value becomes too large or too small to be represented in memory, it can lead to overflow or underflow errors. To prevent this, you can use a conditional statement to check if the float value is within a certain range.
// Result is Inf, because the value is too large to represent in memory
value := 1e300 * 1e300

if math.IsInf(value, 0) {
    fmt.Println("Error: overflow")
}

By using these smart code assertions, you can prevent many of the common errors that can occur when working with float expressions in Go.


Performance

In general, integer operations are faster than floating point operations in most programming languages, including Go. This is because the hardware architectures used today are optimized for integer operations, which make them more efficient in terms of clock cycles needed.

However, there are some performance implications to consider when working with expressions and function calls involving both integers and floating point numbers:

  1. Mixed expressions: When an expression involves both integers and floating point numbers, the integer operands are usually converted to floating point numbers before the calculation is performed. This conversion process can be expensive in terms of performance, especially when dealing with large numbers.

  2. Function calls: Function calls involving floating point operations are usually more expensive than those involving integer operations. This is because floating point calculations require more processing time and use more memory than integer calculations.

  3. Memory usage: Floating point numbers typically use more memory than integers, as they require more storage space for the more significant digits. This means that code that uses a lot of floating point numbers can have a greater memory footprint than code that only uses integers.

  4. Precision: Finally, floating point numbers have a limited precision, which can result in rounding errors in calculations. While this is not necessarily a performance issue, it can impact the accuracy of calculations if not handled properly.

In the end, choosing between integers and floating point numbers depends on the specific use case and the requirements of the program. If the program requires high precision and accuracy, then floating point numbers might be the better choice, even if they are more computationally expensive. Otherwise, if speed and memory usage are important, integers might be the way to go.


Conclusion:

Float number are essential for computations, however sometimes working with integers is much faster. You must avoid conversions as much as possible. Chosing wrong the types, you can loose performance expecially in function calls. Pay attention to unnecesary conversions.


Disclaim. I don't deserve credit becase this is written by ChatGPT. If you learn something, be happy. Post a comment if you find any errors, maybe I can fix them.


Have fun, learn and prosper. ๐Ÿ€๐Ÿ––๐Ÿผ

ย