473,770 Members | 6,713 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

std::stringstre am and floating point accuracy

Is it possible for me to record floats in a std::stringstre am with
100% accuracy? If so how?

Here's a little prog that demonstrates how the default ss loses
accuracy

//-----------------------------------------------------------------------------
#include <sstream>
#include <iostream>
using namespace std;

int main()
{

stringstream ss;

float fOriginal = 0.0000001192092 8955078125f;

ss << fOriginal;

float fRestored;
ss >> fRestored;

cout << endl << fOriginal;
cout << endl << fRestored;

cout << endl << endl << (fOriginal == fRestored); //should be
equal but are not
cout << endl << fOriginal - fRestored; //there's a diff!
return 0;
}

//-----------------------------------------------------------------------------
Oct 20 '05 #1
5 12073
Mr Fish wrote:
Is it possible for me to record floats in a std::stringstre am with
100% accuracy? If so how?
Assuming you want to store a decimal number with a fixed number of
places (i.e., a non-repeating rational number), the only way to ensure
100% accuracy is to store it as a string.
Here's a little prog that demonstrates how the default ss loses
accuracy


[snip code example]

The problem is that representing decimals in a computer is inaccurate.
It's not the stringstream's fault. Here's a good essay to read that
will explain why:

http://docs.sun.com/source/806-3568/ncg_goldberg.html

Kristo

Oct 20 '05 #2
Mr Fish wrote:

Is it possible for me to record floats in a std::stringstre am with
100% accuracy? If so how?

Here's a little prog that demonstrates how the default ss loses
accuracy

//-----------------------------------------------------------------------------
#include <sstream>
#include <iostream>
using namespace std;

int main()
{

stringstream ss;

float fOriginal = 0.0000001192092 8955078125f;


In most implementations I am aware of, float is capable of holding
5 to 6 digits. Apply that to your number, and you get:

1.19209 E -7

everything else in your number is already lost. Even the 9 in the
last digit is already a questionable one. Things get worse if you
do sme arithmetic with that number.

As a minimum: forget 'float' and start using 'double'.
Unless you know what you do and are willing to do it and have the
knowledge to do it and have a very, very, very good reason: never
use float.

--
Karl Heinz Buchegger
kb******@gascad .at
Oct 20 '05 #3
I tried the followind (in C) to test how much was lost when storing in a
float:

float x=0.00000011920 928955078125f;
printf("%.25f\n ", x);

The output is exactly:

0.0000001192092 895507812500

Wow!!
For some reason, Mr Fish chose a number which is exactly representable as a
float var.

Anyway, with arbitrary numbers like 0.0000001226875 8375648363f, the output
is 0.0000001226875 809834382400. You get 8 correct significant digits. But
the correct digits is not the important thing, but the precision of the
stored value, or the error of the representation.

The error in that case is around -2.77e-15. If the original number
represented a length of 12.2 cm (approx. the diameter of a CD) expressed in
strange units like thousands of km [:-)], the error would be equivalent to 3
millionths of a millimeter, or around 30 times the diameter of a hydrogen
atom. Is it that bad?

Let's not just look at the written digits (in decimal), counting how many
are right. Let's look at the accuracy of the values for a particular
application. Decimal is just a representation, which can be as bad as
binary, it's just a different one. We should not see a decimal
representation as the perfect one.

float is not that bad for many, many tasks, but double is sure more suitable
for many others.
"Karl Heinz Buchegger" <kb******@gasca d.at> escribió en el mensaje
news:43******** *******@gascad. at...
Mr Fish wrote:

Is it possible for me to record floats in a std::stringstre am with
100% accuracy? If so how?

Here's a little prog that demonstrates how the default ss loses
accuracy

//--------------------------------------------------------------------------
--- #include <sstream>
#include <iostream>
using namespace std;

int main()
{

stringstream ss;

float fOriginal = 0.0000001192092 8955078125f;


In most implementations I am aware of, float is capable of holding
5 to 6 digits. Apply that to your number, and you get:

1.19209 E -7

everything else in your number is already lost. Even the 9 in the
last digit is already a questionable one. Things get worse if you
do sme arithmetic with that number.

As a minimum: forget 'float' and start using 'double'.
Unless you know what you do and are willing to do it and have the
knowledge to do it and have a very, very, very good reason: never
use float.

--
Karl Heinz Buchegger
kb******@gascad .at

Oct 20 '05 #4
Mr Fish wrote:
Is it possible for me to record floats in a std::stringstre am with
100% accuracy? If so how?


Maybe you find something useful in the following snippet:

#include <iostream>
#include <limits>
#include <cmath>
#include <iomanip>

template < typename Float >
struct precision {

static unsigned int digits ( unsigned int base ) {
return( -
std::log( std::numeric_li mits<Float>::ep silon() )
/
std::log( base ) );
}

};

template < typename Float >
unsigned int sig_digits ( Float const & ) {
return( precision<Float >::digits(10) );
}

int main ( void ) {
std::cout << precision<float >::digits( 10 )
<< " "
<< precision<doubl e>::digits( 10 )
<< '\n';
float x = 2.3345467334234 ;
double y = 12.230912093719 823691836;
std::cout << std::setprecisi on( sig_digits(x) ) << x << '\n';
std::cout << std::setprecisi on( sig_digits(y) ) << y << '\n';
}

Best

Kai-Uwe Bux
Oct 21 '05 #5
Alvaro Segura wrote:

I tried the followind (in C) to test how much was lost when storing in a
float:

float x=0.00000011920 928955078125f;
printf("%.25f\n ", x);

The output is exactly:

0.0000001192092 895507812500

Wow!!
For some reason, Mr Fish chose a number which is exactly representable as a
float var.

Anyway, with arbitrary numbers like 0.0000001226875 8375648363f, the output
is 0.0000001226875 809834382400. You get 8 correct significant digits. But
the correct digits is not the important thing, but the precision of the
stored value, or the error of the representation.

The error in that case is around -2.77e-15.
That is the absolute error.
Completely unimportant. Important is the relative error (the error in relation
to the number)

Add 1.0f to the number above and see what is left from your -2.77e-15

I suggest you try the same thing with the number
1.2268758375648 363f (That's the same number, just a different exponent)
and see if your figures also hold.

float is not that bad for many, many tasks, but double is sure more suitable
for many others.


up to now you have only shown that storing some numbers in float variables
is not that bad if all you do, is printing them.
But that is not the usual thing you do with float, isn't it?
Usually one does some arithmetic with numbers. The more arithmetic you
do, the more things get worse.

--
Karl Heinz Buchegger
kb******@gascad .at
Oct 21 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
7498
by: Woodster | last post by:
I am using std::stringstream to format a string. How can I clear the stringstream variable I am using to "re use" the same variable? Eg: Using std::string std::string buffer; buffer = "value1" + " : " + "value2";
1
4905
by: KidLogik | last post by:
Hello! I am using std::stringstream && std::string to parse a text file -> std::ifstream in; std::string s; std::streamstring ss; int n; I grab each line like so -> std::getline(in,s);
5
4217
by: Marcin Kalicinski | last post by:
Is there a vectorstream class that implements the functionality similar to std::stringstream but with std::vector, not std::string? cheers, Marcin
5
3631
by: ma740988 | last post by:
Consider: #include <iostream> #include <sstream> #include <string> int main ( ) { { double pi = 3.141592653589793238; std::stringstream a;
1
2895
by: magix | last post by:
I got this reply in my previous post a month ago: May I know, how can I automatically create the folder if it doesn't exist ? In previous reply, it said: ------------------------- std::stringstream stream; stream << "C:\\Output\\Output.txt" << std::flush; std::ofstream SaveFile(stream.str().c_str()); The "C:\Output" must already exist?
2
21265
by: akitoto | last post by:
Hi there, I am using the std::stringstream to create a byte array in memory. But it is not working properly. Can anyone help me? Code: #include <vector> #include <sstream> #include <iostream.h>
7
3606
by: Ziyan | last post by:
I am writing a C/C++ program that runs in background (Linux). Therefore, normally no output would be written into standard output. However, sometimes I want to have debug message collected and sent tho network to a client so that errors and debug messages can be displayed simultaneously anywhere. I tried to use a std::stringstream to do the job. I created the stringstream in main() and pass it as pointer into a few threads. Those threads...
7
3314
by: TBass | last post by:
Hi. I wrote a "tag" class to store values. The user gets to store most any type he would need. Instead of getting too complicatated, I decided I would store the value as a stringstream, then overload the SetValue method. .... protected:
3
5906
by: Rune Allnor | last post by:
Hi all. I am trying to use std::stringstream to validate input from a file. The strategy is to read a line from the file into a std::string and feed this std::string to an object which breaks it up into individual elements. The elements can be strings, integers or floating point numbers. In the object where I break the line into elements I use a std::stringstream object to do the actual check:
0
9425
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10225
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10001
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8880
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7415
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6676
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5312
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5449
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3969
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.