W3cubDocs

/C++

std::modf

Defined in header <cmath>
float       modf( float x, float* iptr );
(1)
double      modf( double x, double* iptr );
(2)
long double modf( long double x, long double* iptr );
(3)
1-3) Decomposes given floating point value x into integral and fractional parts, each having the same type and sign as x. The integral part (in floating-point format) is stored in the object pointed to by iptr.

Parameters

x - floating point value
iptr - pointer to floating point value to store the integral part to

Return value

If no errors occur, returns the fractional part of x with the same sign as x. The integral part is put into the value pointed to by iptr.

The sum of the returned value and the value stored in *iptr gives x (allowing for rounding).

Error handling

This function is not subject to any errors specified in math_errhandling.

If the implementation supports IEEE floating-point arithmetic (IEC 60559),

  • If x is ±0, ±0 is returned, and ±0 is stored in *iptr.
  • If x is ±∞, ±0 is returned, and ±∞ is stored in *iptr.
  • If x is NaN, NaN is returned, and NaN is stored in *iptr.
  • The returned value is exact, the current rounding mode is ignored

Notes

This function behaves as if implemented as follows:

double modf(double x, double* iptr)
{
#pragma STDC FENV_ACCESS ON
    int save_round = std::fegetround();
    std::fesetround(FE_TOWARDZERO);
    *iptr = std::nearbyint(x);
    std::fesetround(save_round);
    return std::copysign(std::isinf(x) ? 0.0 : x - (*iptr), x);
}

Example

Compares different floating-point decomposition functions.

#include <iostream>
#include <cmath>
#include <limits>
 
int main()
{
    double f = 123.45;
    std::cout << "Given the number " << f << " or " << std::hexfloat
              << f << std::defaultfloat << " in hex,\n";
 
    double f3;
    double f2 = std::modf(f, &f3);
    std::cout << "modf() makes " << f3 << " + " << f2 << '\n';
 
    int i;
    f2 = std::frexp(f, &i);
    std::cout << "frexp() makes " << f2 << " * 2^" << i << '\n';
 
    i = std::ilogb(f);
    std::cout << "logb()/ilogb() make " << f/std::scalbn(1.0, i) << " * "
              << std::numeric_limits<double>::radix
              << "^" << std::ilogb(f) << '\n';
 
    // special values
    f2 = std::modf(-0.0, &f3);
    std::cout << "modf(-0) makes " << f3 << " + " << f2 << '\n';
    f2 = std::modf(-INFINITY, &f3);
    std::cout << "modf(-Inf) makes " << f3 << " + " << f2 << '\n';
 
}

Possible output:

Given the number 123.45 or 0x1.edccccccccccdp+6 in hex,
modf() makes 123 + 0.45
frexp() makes 0.964453 * 2^7
logb()/ilogb() make 1.92891 * 2^6
modf(-0) makes -0 + -0
modf(-Inf) makes -INF + -0

See also

(C++11)
nearest integer not greater in magnitude than the given value
(function)
C documentation for modf

© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
http://en.cppreference.com/w/cpp/numeric/math/modf