0

I am trying to extract 20 decimals from a variable, but there should be an error with the divide operation, as this program gives me a wrong result:

#include <iostream>
#include <cmath>
using namespace std;
int fracpart(long double input)
{
    long long I;
    I = input * 10;
    return I % 10;
}

int main()
{
    int n = 9, m = 450;
    long double S;
    S = (long double)n/m;
    for(int i=1; i<=20; i++){
        cout << fracpart(S) << " ";
        S *= 10;
    }
    return 0;
}

What I get:

0 1 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9

What I should get:

0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
Bob__
  • 12,361
  • 3
  • 28
  • 42
  • 2
    This looks like it's probably a duplicate of [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken), although I admit I'm not entirely sure what's going on in the code. – Carcigenicate Sep 21 '17 at 16:23
  • I am trying to make a program to get 20 decimals from the division of two numbers. – Josiah Denton Sep 21 '17 at 16:27

2 Answers2

2

You can check the base used by the representation of floating-point types inspecting the value of the macro constant FLT_RADIX (defined in header <cfloat>). As you probably already know, the binary system is used internally by the majority of modern computers, rather then the decimal one.

Now consider a rational number like 1/3. It can't be represented by a finite number of digits in base 10, you'll end up with some approximation, like 0.3333333 and an acceptable error. Note that the same number can be represented in a base 3 system with a finite number of digits (0.1).

The number you are trying to print, 9/450, has a "nice" base 10 representation, 0.02, but it can't be represented in base 2 with absolute precision, even if the division could be performed without adding any error. Don't be misleaded by that '2', consider that 0.02 = 2/100 = 1/50 = 1/(2 * 52), where 1/5 can only be approximated, in base 2.

Anyways, there are methods to achieve what you want, for example using the output manipulators std::setprecision and std::fixed (defined in header <iomanip>) or even writing a (really ugly) custom function. Take a look at the output of this program:

#include <iostream>
#include <cmath>
#include <iomanip>
#include <vector>
#include <cstdint>

// splits a number into its integral and fractional (a vector of digits) parts
std::vector<uint8_t> to_digits (
    long double x, uint8_t precision, long double &integral
);

// Reconstructs the approximated number
long double from_digits (
     long double integral_part, std::vector<uint8_t> &fractional_part
);

int main()
{
    using std::cout;

    int n = 9, m = 450;
    long double S;
    S = static_cast<long double>(n)/m;

    cout << "\nBase 10 representation of calculated value:\n"
         << std::setprecision(70) << S << '\n';
    // This ^^^^^^^^^^^^^^^^^^^^^  will change only how the value is
    // printed, not its internal binary representation

    cout << "\nBase 10 representation of literal:\n"
         << 0.02L << '\n';
    // This ^^^^^ will print the exact same digits

    // the next greater representable value is a worse approximation
    cout << "\nNext representable value:\n"
         << std::nextafter(S, 1.0) << '\n';

    // but you can try to obtain a "better" output
    cout << "\nRounded representation printed using <iomanip> functions:\n"
         << std::setprecision(20) << std::fixed << S << '\n';

    cout << "\nRounded fractional part printed using custom function:\n";
    long double integral_part;
    auto dd = to_digits(S, 20, integral_part);
    for (auto const d : dd)
    {
        cout << static_cast<int>(d);
    }
    cout << '\n';

    // Reversing the process...
    cout << "\nApproximated value (using custom function):\n";
    auto X = from_digits(integral_part, dd);
    cout << std::setprecision(70) << std::fixed << X << '\n';
    cout << std::setprecision(20) << std::fixed << X << '\n';
}

std::vector<uint8_t> to_digits (
    long double x, uint8_t precision, long double &integral
)
{
    std::vector<uint8_t> digits;

    long double fractional = std::modf(x, &integral);

    for ( uint8_t i = 0; i < precision; ++i )
    {
        long double digit;
        fractional = std::modf(fractional * 10, &digit);
        digits.push_back(digit);
    }

    if ( digits.size()  &&  std::round(fractional) == 1.0L )
    {
        uint8_t i = digits.size();
        while ( i )
        {
            --i;
            if ( digits[i] < 9 )
            {
                ++digits[i];
                break;
            }
            digits[i] = 0;
            if ( i == 0 )
            {
                integral += 1.0L;
                break;
            }
        }
    }

    return digits;
}

long double from_digits (
     long double integral_part, std::vector<uint8_t> &fractional_part
)
{
    long double x = 1.0L;
    for ( auto d : fractional_part )
    {
        x *= 10.0L;
        integral_part += d / x;
    }

    return integral_part;
}
Bob__
  • 12,361
  • 3
  • 28
  • 42
-1

I Thought it has happening "because the binary division is not perfectly conversible to decimal numbers", but Bob__ was right! The problem is happening because the long long variable is kind of "problematic". So, I just changed the code and used the functions ceil and round that I mentioned. This time I have tested the code, so I hope that it satisfy your needs.

PS1: Extract the function was really necessary.

PS2: Don't forget to include math.h library.

PS3: And, sorry for the delay in answer.

#include <iostream>
#include <cmath>
#include <math.h>
using namespace std;

int main()
{
    int n = 9, m = 450;
    long double S;
    S = (long double)n/m;
    for(int i=1; i<=20; i++){
        cout << fmod(round(fmod(S * 10,10)), 10) << " ";
        S *= 10;
    }
    return 0;
}

Here is some examples: http://www.cplusplus.com/reference/cmath/trunc/