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 6 3969
"Adam H. Peterson" <ah**@email.byu .edu> wrote in message
news:c1******** ***@acs2.byu.ed u 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(2 0);
// more precision than a double can handle
double x = 9.0839879879798 689898;
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)
> 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
"Adam H. Peterson" <ah**@email.byu .edu> wrote in message
news:c1******** ***@acs2.byu.ed u 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_li mits<T>::digits 10
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)
> 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::ostringstr eam ot;
ot << sqrt2;
std::istringstr eam 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
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::strin g>(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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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?
Without being able to 'split' an iterator, I can't
think of how to do some of the cool things you can do with lazy lists in
Haskell. It seems
quite often you want to be able to do this 'splitting', and if I
|
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 misinterpreted (to 1.0
and -1.0) when I try to read them back in.
#include <fstream>
#include <limits>
|
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 possible to change the behavior of
operator << so it will stream numeric values as their actual values
when an ofstream is in binary mode. I did not, however, find any
information on how this can be accomplished. What is involved in
getting this...
|
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. Similarily, take the
contents of a (part 2) buffer and dump (used sparingly) it into a
struct.
So I found an implementation that handles part 1. Well partially.
#include <ostream>
namespace jngcomp { namespace utils
|
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. It seems that either I can use default serialization
or implement ISerializable. Is there any way to do both (e.g. extend the
default serialization). In other words, I want to be able to implement my
custom serialization code but call the...
| |
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 System.Collections.Comparer has 1 members,
number of members deserialized is 0.
at
System.Runtime.Serialization.Formatters.Binary.ReadObjectInfo.GetMemberTypes(String
|
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 Stream, etc.). It then goes on to
discuss the restriction that streams only read bytes or
byte arrays that the .net framework provides a
StreamReader and StreamWriter class to do type conversions
to and from bytes when using streams.
The second...
|
by: kikisan |
last post by:
I am developing a windows service which utilizes the following classes:
interface IPersistable;
abstract class PersistableObject : IPersistable;
|
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 I am trying to read
from a binary archive using Boost serialization. I am new to this, and
it is possible that I have not understood the usage. In the code
below, the string "faultblock" seems to be causing the problem. The
code crashes in the ia...
|
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
| |
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,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
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...
|
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();...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |