473,804 Members | 3,745 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

conversion problem int <-> double ?

I have two integers i1 and i2, the second of which is guaranteed to be
between 0 and 99, and I encode them into one double:

double encoded = (double)i1 + (double)i2 / (double)100;

So, for example, 324 and 2 become 324.02. Now I want to decode them
using the function given below but it decodes the example as 324 and
1, instead of 324 and 2.

Can anyone tell me what's wrong and how to do this right? (my code see
below)

Thanks!
Markus

#include <iostream>

void decode(double n, int& i1, int& i2){
i1 = int(n);
double rest = n - int(n);
i2 = int(rest * 100.0); // i2 is 1, should be
2
}

int main(int argc, char** argv){
double n = 324.02;
int p;
int i;
decode(n, p, i);
std::cerr << "n=" << n <<", p=" << p << ", i=" << i << std::endl;
return EXIT_SUCCESS;
}
Apr 1 '08 #1
2 3224
On Mar 31, 7:04*pm, Markus Dehmann <markus.dehm... @gmail.comwrote :
I have two integers i1 and i2, the second of which is guaranteed to be
between 0 and 99, and I encode them into one double:

double encoded = (double)i1 + (double)i2 / (double)100;

So, for example, 324 and 2 become 324.02. Now I want to decode them
using the function given below but it decodes the example as 324 and
1, instead of 324 and 2.
The problem is that floating point values usually have a binary
representation. So precise decimal values (such as 324.02) often
cannot be exactly represented with a floating point type. Instead, the
floating point type stores the representable value nearest to the
value specified (for example, the nearest representable value to
324.02 is likely 324.01999).

One solution would be to use decimal floating point arithmetic.
Decimal floating point arithmetic would be able to represent 324.02
exactly. But although support for decimal floating arithmetic is
likely coming to the C++ library, actual implementations of this
feature are not that common.

A more likely (and practical) solution might be to use "fixed-point"
arithmetic. Fixed point arithmetic is completely accurate - up to the
specified resolution. For example, performing the above calculation
with fixed point arithmetic (with 1/100 resolution) might look
something like this:

typedef long Fixed; // in 1/100ths of a unit

Fixed n = 32402;
long p = n/100;
long i = n%100;

Greg

Apr 1 '08 #2
On Apr 2, 6:47 am, Jack Klein <jackkl...@spam cop.netwrote:
On Tue, 1 Apr 2008 01:10:24 -0700 (PDT), James Kanze
<james.ka...@gm ail.comwrote in comp.lang.c++:
On Apr 1, 4:44 am, Jack Klein <jackkl...@spam cop.netwrote:
On Mon, 31 Mar 2008 19:04:01 -0700 (PDT), Markus Dehmann
<markus.dehm... @gmail.comwrote in comp.lang.c++:
double encoded = (double)i1 + (double)i2 / (double)100;
The obvious question is: why? If you really do receive a value
in this format (i.e. integer part and hundredths as two separate
values), and want to treat it as a single value, fine, but then
I don't understand why you want to go the other direction later.
And I can't think of any other reason why one would want to do
this.
I rather think I covered this in my next sentence:
Which is:
This is not a very good idea, as you have found. The
floating point data types in C, and just about every other
computer language, use a fixed number of bits, and that
limits their precision.
I can see reasons why one might want to do this on input. Some
external source is providing an integral value, followed by an
integral number of 100ths, and you want to do various
calculations on those values. Since the input is with an
accuracy of at most a 100th, you'll normally only output with
this accuracy as well, and for most trivial compuations, you can
pretty much ignore the rounding errors (which will be far
smaller).

I can't see a reason why one would want to go back, however.
(Maybe outputting to the same device?)

[...]
Can anyone tell me what's wrong and how to do this
right? (my code see below)
Your basic idea is wrong.
Hard to say without really knowing what his basic idea
is:-). Why does he want to do this? Anyway, two "obvious"
solutions come to mind:
Without knowing his reasoning, I gave him the benefit of the doubt,
and still decided that he was wrong. If he worked for my company, he
wouldn't write code that way a second time after the first code
review.
Even if it was what the requirements spefication demanded?
There are no "non-icky" ways to do this. If its a space issue
of some type, I will bet there are very few platforms where
sizeof(std::div _t) is greater than sizeof(double).
I can't really believe that it's a space issue, since a double
generally is the size of two int, and his input is two ints.
Putting the two values into a std::div_t would retain all the
integer bits with no loss, and still allow easy conversion to
a double if actually needed for some arcane purpose.
I wouldn't call computing a new value an "arcane purpose". And
if some external device is providing input in this format, then
you have to deal with it. The question is why the round trip.
Why does he want to go back to the original format?

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Apr 2 '08 #3

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

Similar topics

1
5660
by: Stub | last post by:
Docs says that "The compiler does not use an explicit constructor to implement an implied conversion of types. It's purpose is reserved explicitly for construction." I put up code of three cases at the bottom. Hope you can help me understand the "explicit" keyword and its usage. Specifically, Is "explicit" keyword only associated with constructor in C++? What's "implied conversion of types"?
7
3262
by: Michael Lehn | last post by:
Hi, I have a question regarding the conversion of objects. When is the conversion done by the constructor and when by the operator. My feeling tells me that the constructor is preferred. But I couldn't find the exact rule in the C++ standard. And what if the classes have template parameters? It would be great if somebody could get me a rough hint where in the
2
6875
by: Alex Sedow | last post by:
Why explicit conversion from SomeType* to IntPtr is not ambiguous (according to standart)? Example: // System.IntPtr class IntPtr { public static explicit System.IntPtr (int); public static explicit System.IntPtr (long);
3
4462
by: Steve Richter | last post by:
here is a warning I am getting in a C++ .NET compile: c:\SrNet\jury\JuryTest.cpp(55) : warning C4927: illegal conversion; more than one user-defined conversion has been implicitly applied while calling the constructor 'MyString::MyString(const wchar_t *)' c:\SrNet\jury\JuryTest.h(21) : see declaration of 'MyString::MyString' The class "StringData" uses a, whatever you call it, operator const
3
1166
by: Mike | last post by:
What are the functions to convert to/from escaped versions for proper HTML viewing? E.g. "< is lt" <--> "&lt is lt" thanks
10
42971
by: Jon Noring | last post by:
Out of curiosity, may a CDATA section appear within an attribute value with datatype CDATA? And if so, how about other attribute value datatypes which accept the XML markup characters? To me, the XML specification seems a little ambiguous on this, so I defer to the XML authorities. Refer to sections 2.4 and 2.7 (it all hinges on if CDATA attribute values are part of markup or not.) Thanks.
0
2294
by: Lou Evart | last post by:
DOCUMENT CONVERSION SERVICES Softline International (SII) operates one of the industry's largest document and data conversion service bureaus. In the past year, SII converted over a million pages to a variety of formats. SII's service bureau has a reputation as being a least-cost provider that can offer a timely turnaround with 100% accuracy. Here are some of the formats SII has converted over the last 20 years:
29
23230
by: aarthi28 | last post by:
Hi, I have written this code, and at the end, I am trying to write a vector of strings into a text file. However, my program is nor compiling, and it gives me the following error when I try to write to the file: error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion) I don't know what I am doing wrong. I have posted my entire program
5
7979
by: amitmool | last post by:
hi, i have used the queue library file and try to use the template as template <class QueueItem> queue <QueueItem>::~queue() // line 25 { } template <class QueueItem> void queue<QueueItem>::push(const QueueItem& entry) // line 42
3
4030
by: webmasterATflymagnetic.com | last post by:
Folks, I'm struggling to put the question together, but I have this problem. I have written an HTML form that I can use for data entry. This uses PHP to write a SQL UPDATE command that gets written to my MySQL database. I can later view this data back in the form. One thing I've noticed happening is if I enter code such as &lt; it gets rewritten as < (ie the less-than sign). Now I don't want this to happen, but something somewhere is...
0
9706
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, 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...
0
9584
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
9160
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
7622
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
6854
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
5525
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...
1
4301
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
2
3822
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2995
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.