In C++, std::fdim(x, y) returns the positive difference of two numbers. That is the same as max(x - y, 0). When x is bigger than y you get the gap, and when it is not you get 0, never a negative number.
This is useful whenever a negative result makes no sense, such as overtime hours, remaining budget, or the amount of a number that goes over a limit. The name means "floating-point positive difference".
std::fdim() is declared in <cmath> and is part of the group Remainder, scale, and compare. These functions split a number, scale it by a power of two, find its remainder, or pick between two numbers. They work directly on the binary form of a double.
Syntax
Include <cmath> and call std::fdim. Start with these lines.
C++
double a = std::fdim(5.0, 3.0); // 2
double b = std::fdim(3.0, 5.0); // 0 (not -2)
double c = std::fdim(2.5, 1.0); // 1.5
Call
What it does
std::fdim(5.0, 3.0)
5 is bigger, so the result is 5 - 3 = 2.
std::fdim(3.0, 5.0)
3 is not bigger than 5, so the result is 0, not -2.
std::fdim(2.5f, 1.0f)
The float overload. Returns 1.5f.
The order matters. fdim(x, y) and fdim(y, x) are not the same, and at most one of them is above zero.
Library declarations
C++
float fdim(float x, float y);
double fdim(double x, double y);
long double fdim(long double x, long double y);
// plus overloads for mixed and integer arguments
Parameters
Parameter
Description
x
Required. The number to subtract from. It can be float, double, long double, or an integer type (converted to double).
y
Required. The number to subtract.
Return Value
Return Value
Description
x - y
The difference, when x is greater than y.
0
Returned when x is less than or equal to y.
NaN
Returned if either argument is NaN.
C++ Examples
Example 1 — Positive Differences
Print fdim() for pairs where x is bigger, smaller, equal, and negative.
Both columns start with the same budget of 100, and show two ways to find what is left.
When 30.5 is spent, both ways agree: 69.5 is left.
When 120 is spent, plain subtraction gives -20, which looks like a negative budget. fdim() says 0, which means nothing is left.
Frequently Asked Questions
std::fdim(x, y) returns the positive difference of x and y. If x is larger than y it returns x - y, and otherwise it returns 0.
x - y when x > y, otherwise +0.0. If either argument is NaN the result is NaN. The type is the promoted type of the arguments.
No. fdim(x, y) is x - y only when x is bigger, and 0 otherwise. The absolute difference is std::fabs(x - y), which is positive in both orders.
It is std::fmax(x - y, 0.0), the bigger of the difference and zero. It is a short way to avoid a negative answer.
Include <cmath> and write std::fdim(). That always works and picks the C++ overloads. The global name ::fdim often works too, but the standard does not promise it, and it may only take a double.