473,473 Members | 2,213 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

C++ streams and serialization

I have an application that uses C++ file streams for storing the state
of complex objects to be later read in, ideally reconstructing the state
of the object as when it was serialized. One issue I'm encountering,
though, is that when I serialize a double and then read it back in, I've
lost precision on the magnitude of 10^-6. Is there a way to tell a
stream to write a double (or any number format) to whatever precision is
required to recover the same number later?

Or should I be doing serialization another way? (I'm hoping I can do it
with streams. I want my data files to be portable, and it's valuable to
be able to look at them in an editor and see what's going on.)

Thanks in advance for any help.

Adam H. Peterson
Jul 22 '05 #1
6 3951
"Adam H. Peterson" <ah**@email.byu.edu> wrote in message
news:c1***********@acs2.byu.edu
I have an application that uses C++ file streams for storing the state
of complex objects to be later read in, ideally reconstructing the
state of the object as when it was serialized. One issue I'm
encountering, though, is that when I serialize a double and then read
it back in, I've lost precision on the magnitude of 10^-6. Is there
a way to tell a stream to write a double (or any number format) to
whatever precision is required to recover the same number later?

Or should I be doing serialization another way? (I'm hoping I can do
it with streams. I want my data files to be portable, and it's
valuable to be able to look at them in an editor and see what's going
on.)

Thanks in advance for any help.

Adam H. Peterson


I am not an expert in this, but a double on Windows is accurate to 15-16
decimal places. If you set the precision of the output stream to some number
greater than this, then the number written out appears to be successfully
recovered, e.g.,

int main()
{
ofstream out("file.txt");
// set precision of output stream to 20
out.precision(20);
// more precision than a double can handle
double x = 9.0839879879798689898;
out << x << endl;
out.close();

ifstream in("file.txt");
double y;
in >> y;
if (x==y)
cout << "success\n";
else
cout << "failure\n";
in.close();
return 0;
}
--
John Carson
1. To reply to email address, remove donald
2. Don't reply to email address (post here instead)

Jul 22 '05 #2
Adam H. Peterson wrote:
I have an application that uses C++ file streams for storing the state
of complex objects to be later read in, ideally reconstructing the state
of the object as when it was serialized. One issue I'm encountering,
though, is that when I serialize a double and then read it back in, I've
lost precision on the magnitude of 10^-6. Is there a way to tell a
stream to write a double (or any number format) to whatever precision is
required to recover the same number later?

Or should I be doing serialization another way? (I'm hoping I can do it
with streams. I want my data files to be portable, and it's valuable to
be able to look at them in an editor and see what's going on.)

Thanks in advance for any help.

Adam H. Peterson


For best portability, convert your numbers to text format. Text format
usually is independent of machine characteristics; including when the
compiler libraries or OS libraries change.

Try reading these sections of the FAQ:
http://www.parashift.com/c++-faq-lit...alization.html
http://www.parashift.com/c++-faq-lit...html#faq-29.16
http://www.eskimo.com/~scs/c-faq/s14.html
http://groups.google.com/groups?hl=e....c%252B%252B.*

If you are storing the double variables and retrieving them without
any conversion, there _should_ be no loss of precision. But then
there are many numbers that cannot be precisely represented by
a fixed real number format.

Also search the web for "IEEE floating point format".

--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book

Jul 22 '05 #3
> I am not an expert in this, but a double on Windows is accurate to 15-16
decimal places. If you set the precision of the output stream to some number
greater than this, then the number written out appears to be successfully
recovered, e.g.,


Thank you for the response. I am actually working under Linux on x86,
but I assume the precision is the same.

I was hoping for a more general (and possibly portable) solution, so
that I could store and retrieve such numbers without knowing beforehand
their intrinsic precision. Is there a way to do this? Perhaps using
std::numerical_limits<>?

Ideally, I would like to be able to do this with a template type T so
that without knowing more about it, I could store and retrieve it
without accuracy loss. But this at least looks like a solution to my
current dilemma. Thank you.

Adam H. Peterson
Jul 22 '05 #4
"Adam H. Peterson" <ah**@email.byu.edu> wrote in message
news:c1***********@acs2.byu.edu
I am not an expert in this, but a double on Windows is accurate to
15-16 decimal places. If you set the precision of the output stream
to some number greater than this, then the number written out
appears to be successfully recovered, e.g.,


Thank you for the response. I am actually working under Linux on x86,
but I assume the precision is the same.

I was hoping for a more general (and possibly portable) solution, so
that I could store and retrieve such numbers without knowing
beforehand their intrinsic precision. Is there a way to do this?
Perhaps using std::numerical_limits<>?

Ideally, I would like to be able to do this with a template type T so
that without knowing more about it, I could store and retrieve it
without accuracy loss. But this at least looks like a solution to my
current dilemma. Thank you.

Adam H. Peterson

std::numeric_limits<T>::digits10

seems to be what you want. Note that setting a precision above that
applicable to a particular type doesn't seem to cause any problems, so you
can always allow a "margin for error" in this respect.
--
John Carson
1. To reply to email address, remove donald
2. Don't reply to email address (post here instead)

Jul 22 '05 #5
> For best portability, convert your numbers to text format. Text format
usually is independent of machine characteristics; including when the
compiler libraries or OS libraries change.

Try reading these sections of the FAQ:
http://www.parashift.com/c++-faq-lit...alization.html
http://www.parashift.com/c++-faq-lit...html#faq-29.16
http://www.eskimo.com/~scs/c-faq/s14.html
http://groups.google.com/groups?hl=e....c%252B%252B.*
If you are storing the double variables and retrieving them without
any conversion, there _should_ be no loss of precision. But then
there are many numbers that cannot be precisely represented by
a fixed real number format.

Also search the web for "IEEE floating point format".


Portability is one of the reason I'm using text streams. (Other reasons
are transparency and clarity.) So I thought that that was what I was doing.

It appears to me that I am in fact getting an accuracy loss in this
process. This program appears to demonstrate that this occurs:

#include <iostream>
#include <sstream>
#include <cmath>

int signed main() {
double sqrt2=std::sqrt(2.0);
std::ostringstream ot;
ot << sqrt2;
std::istringstream it(ot.str());
double sqrt2io;
it >> sqrt2io;
std::cout << (sqrt2-sqrt2io) << std::endl;
}

// Output on my machine (GCC 3.2.2, RH Linux 9) is:
// 3.56237e-06
// I would expect 0 if the same number was being read.

But this is the naive approach to it and perhaps I'm missing some
subtleties. (If so, I would love to be enlightened.)

On a side note, I _know_ I read the faq cover to cover, but I'm positive
this serialization stuff wasn't in there. I assume it was added since
(about six years ago), which I suppose is good, meaning it's adapting to
new needs. I guess I better rebrowse it.

But it doesn't look like the faq (or at least this page of it) addresses
my precision issues.

Anyway, thank you for your time to respond.

Adam H. Peterson
Jul 22 '05 #6
If anyone is interested, I think I've found a general solution. Instead
of using:

double x=whatever;
file << x;

.... I use:

double x=whatever;
file << boost::lexical_cast<std::string>(x);

.... it seems to store enough digits to reconstruct the number. (I get a
difference of zero in my test program I posted earlier.

Of course, you have to have boost installed for this solution, but
that's not a problem for me.

Thanks for the help, those who posted or read my musings.

Adam H. Peterson
Jul 22 '05 #7

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

Similar topics

8
by: Ronald Legere | last post by:
The new itertools stuff is pretty cool. One thing that bothers me though is that there seems to be no way to copy an iterator. How does one work around this? Is there a trick that I am missing? ...
6
by: Gustav Lead | last post by:
Hi all, I have trouble reading back floating point data from a file. It appears as if the tokens for positive and negative infinity (1.#INF and -1.#INF) that my implementation writes get...
3
by: Tron Thomas | last post by:
What does binary mode for an ofstream object do anyway? Despite which mode the stream uses, operator << writes numeric value as their ASCII representation. I read on the Internet that it is...
4
by: ma740988 | last post by:
A few days ago I recieved yet again advice on implementing a buffer of bytes. At issue: (part 1) how do I take the contents of a struct, then dump (used sparingly) it into a byte buffer. ...
3
by: Aaron Clamage | last post by:
Hi, I'm not sure that if this is the right forum, but any help would be greatly appreciated. I am porting some java serialization code to c# and I can't figure out the correct way to do it. ...
3
by: Alexander | last post by:
When i store rule on PC with .NET.SP1 i cant restore them from PC without SP1. An i get this Error: System.Runtime.Serialization.SerializationException: Possible Version mismatch. Type...
1
by: Chris | last post by:
I'm reading up on streams and I have two articles that seem to conflict with each other. One article describes streams and lists a few of the major ones (FileStream, Memory Stream, Network...
1
by: kikisan | last post by:
I am developing a windows service which utilizes the following classes: interface IPersistable; abstract class PersistableObject : IPersistable;
2
by: mkvenkit.vc | last post by:
Hello, I hope this is the right place to post a question on Boost. If not, please let me know where I can post this message and I will do so. I am having a strange problem with std::string as...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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...
1
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...
0
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,...
1
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...
0
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...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
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 ...
1
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.