0

I found some weird things in my code while playing a few of numbers.

Here is the code I am working on.

#include<iostream>
using namespace std;

int main()
{
    double f1,f2;

    cout << "Enter the floating number" << endl;
    cin >> f1;

    f2 = 0.00255;

    return 0;
}

Adding a breakpoint before return, I checked the value of f1 and f2.

Then, I found a difference between f1 and f2, even though they must be identical.

Below is what I compared in the debugging mode.

enter image description here

  • Q1. Why are those values different?

    The difference is so marginal that they seem identical as 0.00255 but sometimes that small difference could be important in mathematical application.

  • Q2. How can I make them identical as 0.0025500000000000002?

Community
  • 1
  • 1
9mile
  • 1
  • *I found some weird things in my code while playing a few of numbers.* -- This is not weird, unless you are not aware that binary floating point is not decimal. – PaulMcKenzie May 18 '20 at 15:29
  • @NathanOliver this duplicate does explain inaccuracies in **floating-point math**, but no explicit math is being performed in this question. What is being observed here is probably not an artifact of IEEE-754, but more likely an artifact of Intel-compatible CPUs sometimes using 80 bit floats that get truncated to 64-bit iff stored in memory. – Drew Dormann May 18 '20 at 15:29
  • 1
    @DrewDormann `cin` has to convert the text the user entered into a number. That involves math. – NathanOliver May 18 '20 at 15:31
  • *How can I make them identical as 0.0025500000000000002?* -- The question to you is why you want them identical, down to the last digit of precision? What type of applications are you developing? Financial? Scientific? – PaulMcKenzie May 18 '20 at 15:32
  • @PaulMcKenzie it affects subsequent calculation. The application is in scientific area. – 9mile May 18 '20 at 15:43
  • @9mile, the answer you may be looking for is that applications that require exact mathematical precision should not use [types that are inexact](https://en.cppreference.com/w/cpp/types/numeric_limits/is_exact). `double` is fast, at the cost of this inaccuracy. – Drew Dormann May 18 '20 at 15:44
  • As noted, if you want exact math, then use a third-party, exact type that supports fixed point math (or a big integer number library). For example, applications that usually need exact types are financial based. Scientific applications rarely, if ever need the full precision, and can withstand the least significant set of digits being "off". – PaulMcKenzie May 18 '20 at 15:54
  • @Drew Dormann, Paul Mckenzie, i undersatand what you mean. I will search types for my study. – 9mile May 19 '20 at 01:32

0 Answers0