0

So, I'm new to C++ and I have come across a weird behavior. This is my code

#include <iostream>
#include <iomanip>

using namespace std; 

int main()
{
    float fValue = 123.12;
    cout << fixed << "Value: " << fValue << endl;
    return 0;
}

Now the output is kind of weird.

For different fValues the output is different e.g:

fValue: 123.12 Output: 123.120003

fValue: 1234.12 Output: 1234.119995

fValue: 1234.1231 Output: 1234.123047

So, not sure what I'm doing wrong here or what the problem is.

c0mp13x
  • 55
  • 1
  • 6
  • 8
    [What Every Computer Scientist Should Know About Floating-Point Arithmetic](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – Maxim Egorushkin Jul 09 '20 at 12:23
  • 3
    Also https://stackoverflow.com/questions/588004/is-floating-point-math-broken – Cory Kramer Jul 09 '20 at 12:25
  • @MaximEgorushkin Looks like a very in-depth explanation and I'll be taking a look at it soon as I can. – c0mp13x Jul 09 '20 at 12:32
  • @CoryKramer Regarding your response, I get it. It happens, it's how things work. But how does one prevent these things from actually messing up your program. Tolerance value sounds a bit hard for a new programmer to actually figure it out. So, is there a short term solution to actually calculate with full precision? – c0mp13x Jul 09 '20 at 12:34
  • 1
    @c0mp13x computers have limited precision. If you want better precision than what a `float` offers, use a `double`. It's still limited to a certain number of bits - but it's more precise than a `float`. – Ted Lyngmo Jul 09 '20 at 12:46
  • 1
    @TedLyngmo I see. Thanks, I'll try to see which can be implemented better, based on what I am working. – c0mp13x Jul 09 '20 at 12:58
  • @c0mp13x If the precision of a `double` isn't good enough, you may try `long double`. If that's not enough you'll need some external BigNum library. – Ted Lyngmo Jul 09 '20 at 13:02
  • Note that on Visual Studio`long double` is the same as `double` – drescherjm Jul 09 '20 at 14:03
  • 1
    @TedLyngmo Got it. Didn't know those libraries existed, nice to know but I don't think I'll be ever using them for the near future. – c0mp13x Jul 09 '20 at 14:38
  • @drescherjm I am using VS Code for macOS and sizeof does not agree with that statement here :) I'll be sure to check it out on a Windows platform. – c0mp13x Jul 09 '20 at 14:39
  • Oh sorry. I meant Visual Studio (using the Microsoft compiler) not Visual Studio Code. I guess I should have paid more attention to the tags. – drescherjm Jul 09 '20 at 15:09
  • @drescherjm Yeah, no problem man! – c0mp13x Jul 09 '20 at 20:37

0 Answers0