Prev: const is an overrated concept that is a source of extra typing and maintenan
Next: Project to recover UnderC C/C++ interpreter
From: Hei on 25 Mar 2010 19:37 Hi, I just wonder whether there is an efficient way to shift/move the decimal place of a double by x (an int) to the left without losing precision. e.g. shifting the decimal place of 11096.2345 by 2 => 110.962345 Thanks in advance. -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ]
From: Ulrich Eckhardt on 25 Mar 2010 22:37 Hei wrote: > I just wonder whether there is an efficient way to shift/move the > decimal place of a double by x (an int) to the left without losing > precision. > > e.g. shifting the decimal place of 11096.2345 by 2 => 110.962345 Just divide by 100. The reason why there is no "perfect" way for that is that most floating point implementations store the exponent for a binary number, not for decimal. That means that if you want to modify just the exponent, which would be the equivalent of shifting the radix separator, you can only do so in powers of two, not powers of ten. For powers of ten, you have to approximate the exponent and then modify the base, but that base modification always bears the danger of losing precision. Uli -- Sator Laser GmbH Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932 [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ]
From: Thomas Richter on 26 Mar 2010 00:16
Hei wrote: > Hi, > > I just wonder whether there is an efficient way to shift/move the > decimal place of a double by x (an int) to the left without losing > precision. The implementation defines the number format used to represent doubles, but on most implementations I know, the binary IEEE format is used for that. With this format, a division by ten will typically generate a loss of precision that is unavoidable. > e.g. shifting the decimal place of 11096.2345 by 2 => 110.962345 If you need to preserve precision, I suggest to look into additional libraries that support other numerical formats. GNUs "bignum" library might be of interest. Or you could represent your numbers as fractions if that is an option. Greetings, Thomas -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ] |