Skip to content
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
---
title: Learn about floating point rounding on Arm
title: Explore floating-point differences between x86 and Arm

draft: true
cascade:
draft: true

minutes_to_complete: 30

who_is_this_for: Developers porting applications from x86 to Arm who observe different floating point values on each platform.
who_is_this_for: This is an introductory topic for developers who are porting applications from x86 to Arm and want to understand how floating-point behavior differs between these architectures - particularly in the context of numerical consistency, performance, and debugging subtle bugs.

learning_objectives:
- Understand the differences between floating point numbers on x86 and Arm.
- Understand factors that affect floating point behavior.
- How to use compiler flags to produce predictable behavior.
- Identify key differences in floating-point behavior between the x86 and Arm architectures.
- Recognize the impact of compiler optimizations and instruction sets on floating-point results.
- Apply compiler flags and best practices to ensure consistent floating-point behavior across
platforms.

prerequisites:
- Access to an x86 and an Arm Linux machine.
- Basic understanding of floating point numbers.
- Familiarity with floating-point numbers.

author: Kieran Hejmadi

Expand All @@ -38,7 +39,7 @@ shared_between:

further_reading:
- resource:
title: G++ Optimisation Flags
title: G++ Optimization Flags
link: https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html
type: documentation
- resource:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,41 +1,54 @@
---
title: Floating Point Representations
title: "Floating-Point Representation"
weight: 2

### FIXED, DO NOT MODIFY
layout: learningpathall
---

## Review of floating point numbers
## Review of floating-point numbers

If you are unfamiliar with floating point number representation, you can review [Learn about integer and floating-point conversions](/learning-paths/cross-platform/integer-vs-floats/introduction-integer-float-types/). It covers different data types and explains data type conversions.
{{% notice Learning tip%}}
If you are new to floating-point numbers, and would like some further information, see
the Learning Path [Learn about integer and floating-point conversions](/learning-paths/cross-platform/integer-vs-floats/introduction-integer-float-types/). It covers data types and conversions.
{{% /notice %}}

Floating-point numbers are a fundamental representation of real numbers in computer systems, enabling efficient storage and computation of decimal values with varying degrees of precision. In C/C++, floating point variables are created with keywords such as `float` or `double`. The IEEE 754 standard, established in 1985, is the most widely used format for floating-point arithmetic, ensuring consistency across different hardware and software implementations.
Floating-point numbers represent real numbers using limited precision, enabling efficient storage and computation of decimal values. In C/C++, floating-point variables are created with keywords such as `float` or `double`. The IEEE 754 standard, established in 1985, defines the most widely used format for floating-point arithmetic, ensuring consistency across hardware and software.

IEEE 754 defines two primary formats: single-precision (32-bit) and double-precision (64-bit).
IEEE 754 specifies two primary formats: single-precision (32-bit) and double-precision (64-bit).

Each floating-point number consists of three components:
- **sign bit**. (Determining positive or negative value)
- **exponent** (defining the scale or magnitude)
- **significand** (also called the mantissa, representing the significant digits of the number).

The standard uses a biased exponent to handle both large and small numbers efficiently, and it incorporates special values such as NaN (Not a Number), infinity, and subnormal numbers for robust numerical computation. A key feature of IEEE 754 is its support for rounding modes and exception handling, ensuring predictable behavior in mathematical operations. However, floating-point arithmetic is inherently imprecise due to limited precision, leading to small rounding errors.
- **Sign bit**: Determines the sign (positive or negative).
- **Exponent**: Sets the scale or magnitude.
- **Significand**: Holds the significant digits in binary.

The graphic below illustrates various forms of floating point representation supported by Arm, each with varying number of bits assigned to the exponent and mantissa.
The standard uses a biased exponent to handle both large and small numbers efficiently, and it incorporates special values such as NaN (Not a Number), infinity, and subnormal numbers. It supports rounding modes and exception handling, which help ensure predictable results. However, floating-point arithmetic is inherently imprecise, leading to small rounding errors.

The graphic below shows various forms of floating-point representation supported by Arm, each with varying number of bits assigned to the exponent and significand.

![floating-point](./floating-point-numbers.png)

## Rounding errors

Since computers use a finite number of bits to store a continuous range of numbers, rounding errors are introduced. The unit in last place (ULP) is the smallest difference between two consecutive floating-point numbers. It measures floating-point rounding error, which arises because not all real numbers can be exactly represented.
Because computers use a finite number of bits to store a continuous range of numbers, rounding errors are introduced. The unit in last place (ULP) is the smallest difference between two consecutive floating-point numbers. It quantifies the rounding error, which arises because not all real values can be exactly represented.

Operations round results to the nearest representable value, introducing small discrepancies. This rounding error, often measured in ULPs, reflects how far the computed value may deviate from the exact mathematical result.

When an operation is performed, the result is rounded to the nearest representable value, introducing a small error. This error, often measured in ULPs, indicates how close the computed value is to the exact result. For a simple example, if a floating-point schema with 3 bits for the mantissa (precision) and an exponent in the range of -1 to 2 is used, the possible values are represented in the graph below.
For example, with 3 bits for the significand and an exponent range of -1 to 2, only a limited set of values can be represented. The diagram below illustrates these values.

![ulp](./ulp.png)

Key takeaways:

- ULP size varies with the number’s magnitude.
- Larger numbers have bigger ULPs due to wider spacing between values.
- Smaller numbers have smaller ULPs, reducing quantization error.
- ULP behavior impacts numerical stability and precision in computations.
- ULP size increases with magnitude.
- Larger numbers have wider spacing between values (larger ULPs).
- Smaller numbers have tighter spacing (smaller ULPs), reducing quantization error.
- ULP behavior impacts numerical stability and precision.

{{% notice Learning tip %}}
Keep in mind that rounding and representation issues aren't bugs — they’re a consequence of how floating-point math works at the hardware level. Understanding these fundamentals is essential when porting numerical code across architectures like x86 and Arm.
{{% /notice %}}


In the next section, you'll explore how x86 and Arm differ in how they implement and optimize floating-point operations — and why this matters for writing portable, accurate software.
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,13 @@ layout: learningpathall

## What are the differences in behavior between x86 and Arm floating point?

Architecture and standards define floating point overflows and truncations in different ways.
Although both x86 and Arm generally follow the IEEE 754 standard for floating-point representation, their behavior in edge cases — like overflow and truncation — can differ due to implementation details and instruction sets.

You can see this by comparing an example application on an x86 and an Arm Linux system.
You can see this by comparing an example application on both an x86 and an Arm Linux system.

You can use any Linux systems for this example. If you are using AWS, you can use EC2 instance types
`t3.micro` and `t4g.small` running Ubuntu 24.04.
Run this example on any Linux system with x86 and Arm architecture; on AWS, use EC2 instance types `t3.micro` and `t4g.small` with Ubuntu 24.04.

To learn about floating point differences, use an editor to copy and paste the C++ code below into a new file named `converting-float.cpp`.
To learn about floating-point differences, use an editor to copy and paste the C++ code below into a new file named `converting-float.cpp`:

```cpp
#include <iostream>
Expand Down Expand Up @@ -61,7 +60,7 @@ int main() {
}
```

If you need to install the `g++` compiler, run the commands below.
If you need to install the `g++` compiler, run the commands below:

```bash
sudo apt update
Expand All @@ -76,23 +75,25 @@ The compile command is the same on both systems.
g++ converting-float.cpp -o converting-float
```

For easy comparison, the image below shows the x86 output (left) and Arm output (right). The highlighted lines show the difference in output.
For easy comparison, the image below shows the x86 output (left) and Arm output (right). The highlighted lines show the difference in output:

![differences](./differences.png)

As you can see, there are several cases where different behavior is observed. For example when trying to convert a signed number to a unsigned number or dealing with out-of-bounds numbers.
As you can see, there are several cases where different behavior is observed. For example when trying to convert a signed number to an unsigned number or dealing with out-of-bounds numbers.

## Removing hardcoded values with macros

The above differences show that explicitly checking for specific values will lead to unportable code.

For example, consider the function below. The code checks if the value is 0. The value an x86 machine will convert a floating point number that exceeds the maximum 32-bit float value. This is different from Arm behavior leading to unportable code.
For example, the function below checks if the casted result is `0`. This can be misleading — on x86, casting an out-of-range floating-point value to `uint32_t` may wrap to `0`, while on Arm it may behave differently. Relying on these results makes the code unportable.



```cpp
void checkFloatToUint32(float num) {
uint32_t castedNum = static_cast<uint32_t>(num);
if (castedNum == 0) {
std::cout << "The casted number is 0, indicating the float could out of bounds for uint32_t." << std::endl;
std::cout << "The casted number is 0, indicating that the float is out of bounds for uint32_t." << std::endl;
} else {
std::cout << "The casted number is: " << castedNum << std::endl;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@ layout: learningpathall

One cause of different outputs between x86 and Arm stems from the order of instructions and how errors are propagated. As a hypothetical example, an Arm system may decide to reorder the instructions that each have a different rounding error so that subtle changes are observed.

It is possible that 2 functions that are mathematically equivalent will propagate errors differently on a computer.
It is possible that two functions that are mathematically equivalent will propagate errors differently on a computer.

Functions `f1` and `f2` are mathematically equivalent. You would expect them to return the same value given the same input.

If the input is a very small number, `1e-8`, the error is different due to the loss in precision caused by different operations. Specifically, `f2` avoids the subtraction of nearly equal number. For a full description look into the topic of [numerical stability](https://en.wikipedia.org/wiki/Numerical_stability).
If the input is a very small number, `1e-8`, the error is different due to the loss in precision caused by different operations. Specifically, `f2` avoids subtracting nearly equal numbers for clarity. For a full description look into the topic of [numerical stability](https://en.wikipedia.org/wiki/Numerical_stability).

Use an editor to copy and paste the C++ code below into a file named `error-propagation.cpp`.
Use an editor to copy and paste the C++ code below into a file named `error-propagation.cpp`:

```cpp
#include <stdio.h>
Expand Down Expand Up @@ -53,13 +53,13 @@ int main() {
}
```

Compile the code on both x86 and Arm with the following command.
Compile the code on both x86 and Arm with the following command:

```bash
g++ -g error-propagation.cpp -o error-propagation
```

Running the 2 binaries shows that the second function, `f2`, has a small rounding error on both architectures. Additionally, there is a further rounding difference when run on x86 compared to Arm.
Running the two binaries shows that the second function, `f2`, has a small rounding error on both architectures. Additionally, there is a further rounding difference when run on x86 compared to Arm.

Running on x86:

Expand Down
Original file line number Diff line number Diff line change
@@ -1,22 +1,20 @@
---
title: Minimizing variability across platforms
title: Minimizing floating-point variability across platforms
weight: 5

### FIXED, DO NOT MODIFY
layout: learningpathall
---

## How can I minimize variability across x86 and Arm?
## How can I minimize floating-point variability across x86 and Arm?

The line `#pragma STDC FENV_ACCESS ON` is a directive that informs the compiler to enable access to the floating-point environment.
The line `#pragma STDC FENV_ACCESS ON` is a directive that informs the compiler to enable access to the floating-point environment. This is part of the C++11 standard and ensures that the program can properly handle floating-point exceptions and rounding modes, enabling your program to continue running if an exception is thrown.

This is part of the C++11 standard and is used to ensure that the program can properly handle floating-point exceptions and rounding modes enabling your program to continue running if an exception is thrown.

In the context below, enabling floating-point environment access is crucial because the functions you are working with involve floating-point arithmetic, which can be prone to precision errors and exceptions such as overflow, underflow, division by zero, and invalid operations. This is not necessary for this example, but is included because it may be relevant for your own application.
In the context below, enabling floating-point environment access is crucial because the functions in this example involve floating-point arithmetic, which can be prone to precision errors and exceptions such as overflow, underflow, division by zero, and invalid operations. Although not strictly necessary for this example, the directive is included because it may be relevant for your own applications.

This directive is particularly important when performing operations that require high numerical stability and precision, such as the square root calculations in functions below. It allows the program to manage the floating-point state and handle any anomalies that might occur during these calculations, thereby improving the robustness and reliability of your numerical computations.

Use an editor to copy and paste the C++ file below into a file named `error-propagation-min.cpp`.
Use an editor to copy and paste the C++ file below into a file named `error-propagation-min.cpp`:

```cpp
#include <cstdio>
Expand Down Expand Up @@ -63,13 +61,13 @@ int main() {

Compile on both computers, using the C++ flag, `-frounding-math`.

You should use this flat when your program dynamically changes the floating-point rounding mode or needs to run correctly under different rounding modes. In this example, it results in a predictable rounding mode on function `f1` across x86 and Arm.
You should use this flag when your program dynamically changes the floating-point rounding mode or needs to run correctly under different rounding modes. In this example, it ensures that `f1` uses a predictable rounding mode across both x86 and Arm.

```bash
g++ -o error-propagation-min error-propagation-min.cpp -frounding-math
```

Running the new binary on both systems leads to function, `f1` having a similar value to `f2`. Further the difference is now identical across both Arm64 and x86.
Running the new binary on both systems shows that function `f1` produces a value nearly identical to `f2`, and the difference between them is now identical across both Arm64 and x86.

Here is the output on both systems:

Expand All @@ -81,9 +79,9 @@ Difference (f1 - f2) = -1.7887354748e-17
Final result after magnification: 0.0000999982
```

G++ provides several compiler flags to help balance accuracy and performance such as`-ffp-contract` which is useful when lossy, fused operations are used, such as fused-multiple.
G++ provides several compiler flags to help balance accuracy and performance. For example, `-ffp-contract` is useful when lossy, fused operations are used, such as fused-multiple.

Another example is `-ffloat-store` which prevents floating point variables from being stored in registers which can have different levels of precision and rounding.
Another example is `-ffloat-store` which prevents floating-point variables from being stored in registers which can have different levels of precision and rounding.

You can refer to compiler documentation for more information about the available flags.
You can refer to compiler documentation for more information on the flags available.