473,789 Members | 2,441 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Avoiding float

I need to do just a few multiplies of long integers and have a divide
by ten. Can I avoid using floats? Can I use two longs as a 64 bit value
somehow? Thanks.

Sep 7 '06
27 2877
Keith Thompson wrote:
CBFalconer <cb********@yah oo.comwrites:
ga*****@hotmail .com wrote:
Konstantin Miller wrote:
ga*****@hotmail .com wrote:

I need to do just a few multiplies of long integers and have a
divide by ten. Can I avoid using floats? Can I use two longs
as a 64 bit value somehow? Thanks.

Can you specify more clearly what you want to do? :-)

I have some long values in Liters and I want to convert to gallons
(and back). If I could do integer multiplication and divide by 10
I could avoid the float library. Thanks.
[1] c:\stds>units gallon litre
* 3.7854118
/ 0.26417205

As you can plainly see, the conversion factors are nowhere near
integral. Besides which, no float library should be required to do
the multiplication or division. The final output is another
matter.

The exact ratio, in lowest terms, is 473176473 / 125000000 (or,
expressed as a real number, exactly 3.785411784). (1 liter is 1000
cubic centimeters; 1 US gallon is 231 cubic inches; 1 inch is 2.54
centimeters.)

I don't know where the "divide by 10" comes from, but I suspect the OP
is attempting to do premature optimization.
[...]
Well I thought rather than using 3.785 I could use 3785 and then divide
the result by 1000. That is where my "divide by 10" comes from. Thanks.

Sep 7 '06 #11
Keith Thompson wrote:
CBFalconer <cb********@yah oo.comwrites:
>ga*****@hotmail .com wrote:
>>Konstantin Miller wrote:
ga*****@hotmail .com wrote:

I need to do just a few multiplies of long integers and have a
divide by ten. Can I avoid using floats? Can I use two longs
as a 64 bit value somehow? Thanks.

Can you specify more clearly what you want to do? :-)

I have some long values in Liters and I want to convert to gallons
(and back). If I could do integer multiplication and divide by 10
I could avoid the float library. Thanks.

[1] c:\stds>units gallon litre
* 3.7854118
/ 0.26417205

As you can plainly see, the conversion factors are nowhere near
integral. Besides which, no float library should be required to do
the multiplication or division. The final output is another
matter.

The exact ratio, in lowest terms, is 473176473 / 125000000 (or,
expressed as a real number, exactly 3.785411784). (1 liter is 1000
cubic centimeters; 1 US gallon is 231 cubic inches; 1 inch is 2.54
centimeters.)
This is pure coincidence, but a few hours ago I published (here) my
ratapprx program for rational approximations. Applied to this
problem it gives:

[1] c:\c\ratapprx>r atapprx 3.7854118 10000
Usage: ratvalue [number [maxnumerator]]
number defaults to PI, maxnumerator to 500
Rational approximation to 3.7854118000000 00
2 / 1 = 2.0000000000000 00 with error 1.7854118000000 00
3 / 1 = 3.0000000000000 00 with error 0.7854118000000 00
4 / 1 = 4.0000000000000 00 with error 0.2145882000000 00
11 / 3 = 3.6666666666666 67 with error 0.1187451333333 33
15 / 4 = 3.7500000000000 00 with error 0.0354118000000 00
19 / 5 = 3.8000000000000 00 with error 0.0145882000000 00
34 / 9 = 3.7777777777777 78 with error 0.0076340222222 22
53 / 14 = 3.7857142857142 86 with error 0.0003024857142 86
458 / 121 = 3.7851239669421 49 with error 0.0002878330578 51
511 / 135 = 3.7851851851851 85 with error 0.0002266148148 15
564 / 149 = 3.7852348993288 59 with error 0.0001769006711 41
617 / 163 = 3.7852760736196 32 with error 0.0001357263803 68
670 / 177 = 3.7853107344632 77 with error 0.0001010655367 23
723 / 191 = 3.7853403141361 26 with error 0.0000714858638 74
776 / 205 = 3.7853658536585 36 with error 0.0000459463414 63
829 / 219 = 3.7853881278538 81 with error 0.0000236721461 19
882 / 233 = 3.7854077253218 89 with error 0.0000040746781 11
2699 / 713 = 3.7854137447405 33 with error 0.0000019447405 33
3581 / 946 = 3.7854122621564 48 with error 0.0000004621564 48
4463 / 1179 = 3.7854113655640 37 with error 0.0000004344359 63
8044 / 2125 = 3.7854117647058 82 with error 0.0000000352941 18

So I guess it has definite uses in allowing elimination of
overflows in calculations such as the OPs. I doubt if he needs
anything better than 882 / 233 (or 233 / 882 for the inverse
conversion). If he just installs the magic numbers without comment
he deserves anything that happens to him.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>

Sep 7 '06 #12
CBFalconer <cb********@yah oo.comwrites:
This is pure coincidence, but a few hours ago I published (here) my
ratapprx program for rational approximations. Applied to this
problem it gives:

[1] c:\c\ratapprx>r atapprx 3.7854118 10000
[...]
8044 / 2125 = 3.7854117647058 82 with error 0.0000000352941 18
My HP 32SII calculator gives exactly the same approximation when
I type 3.7854118 and hit the FDISP (fraction display) button.[*]
Amazing.
[*] Well, it displays it as 3 1669 / 2125, but it's the same
fraction.
--
Ben Pfaff
email: bl*@cs.stanford .edu
web: http://benpfaff.org
Sep 7 '06 #13
Keith Thompson wrote:
I don't know where the "divide by 10" comes from, but I suspect the OP
is attempting to do premature optimization.
Avoiding floating point may itself be a premature optimization, and
without profiling a specific architecture, how do we actually know it
would be slower than integer arithmetic? FPU designs are pretty
sophisticated nowadays, and if it turns out that the FPU can do some
computations in its pipeline while the ALU is busy with other stuff, it
could very well turn out that float is no less efficient. This seems
even more likely when you're throwing in extra divide operations in
order to work with rational expressions.

But I'm not saying anything you didn't say already. As complicated as
pipeline architectures are, how do can you hope to guess what will be
efficient and what will not?
Sep 7 '06 #14
Ben Pfaff said:
CBFalconer <cb********@yah oo.comwrites:
>This is pure coincidence, but a few hours ago I published (here) my
ratapprx program for rational approximations. Applied to this
problem it gives:

[1] c:\c\ratapprx>r atapprx 3.7854118 10000

[...]
> 8044 / 2125 = 3.7854117647058 82 with error 0.0000000352941 18

My HP 32SII calculator gives exactly the same approximation when
I type 3.7854118 and hit the FDISP (fraction display) button.[*]
Amazing.
It might not be entirely coincidental. IIRC Chuck has done quite a bit of
work in the calculator industry. You might just be comparing his code
against - well, his code. :-)

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Sep 7 '06 #15
ga*****@hotmail .com wrote:
Konstantin Miller wrote:
>ga*****@hotmail .com wrote:
>>I need to do just a few multiplies of long integers and have a
divide by ten. Can I avoid using floats? Can I use two longs
as a 64 bit value somehow? Thanks.
Hi!

Can you specify more clearly what you want to do? :-)

Konstantin

I have some long values in Liters and I want to convert to gallons (and
back). If I could do integer multiplication and divide by 10 I could
avoid the float library. Thanks.
Not so simple I'd guess. Have a look at this..

One survey foot = 0.3048006096 meters.
One statute mile = 1.6093472187 kilometers.
One inch = 0.0254 meters (exactly).
One foot = 0.3048 meters (exactly).
One yard = 0.9144 meters (exactly).
One cubic inch = 16.387064 cubic centimeters (exactly).
One cubic foot = 28.316846592 liters (exactly).
One cubic foot = 7.48051948 US gallons.
One US gallon = 3.785411784 liters (exactly).
One ounce (fluid) = 29.573529562 milliliters.
One pound = 453.59237 grams (exactly).
One pound = 7000 grains (exactly).
One ounce (avdp) = 28.349523125 grams (exactly).
One ounce (avdp) = 437.5 grains (exactly).
One grain = 64.79891 milligrams (exactly).
One carat = 3.08647167 grains.

One meter = 39.37007874 inches.
One meter = 3.280839895 feet.
One meter = 1.093613298 yards.
One kilogram = 2.204622622 pounds.
One gram = 15.43235835 grains.
One gram = 0.035273962 ounces.
One US gallon (water) weighs 8.345404 pounds.
Ten pounds of water is 1.198264 US gallons.

Doing stuff like this without floating point is something I don't want
to even think about.

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Sep 8 '06 #16

Walter Roberson wrote:
In article <11************ **********@b28g 2000cwb.googleg roups.com>,
<ga*****@hotmai l.comwrote:
I need to do just a few multiplies of long integers and have a divide
by ten. Can I avoid using floats? Can I use two longs as a 64 bit value
somehow?

You will have to synthesize the arithmetic to do this, but it is not
difficult if you are only doing it for a pair.

Below, let W be the number of bits being multiplied at a time,
and let ** represent exponentiation

Then
(Ahigh * 2**W + Alow) * (Bhigh * 2**W + Blow) is

Ahigh * Bhigh * 2**(W+W) + Ahigh * Blow * 2**W +
Alow * Bhigh * 2**W + Alow * Blow

which is

(Ahigh * Bhigh) * 2**(2*W) +
(Ahigh * Blow + Alow * Bhigh) * 2**W +
Alow * Blow
Now the trick: let Ahigh be the high bits of the original unsigned long A
and let Alow be the low bits -- e.g.,

Alow = A & ~(1L<<W);
Ahigh = A >W;

and similiarily for Bhigh and Blow derived from B. For example, if your
unsigned long can hold 32 bits, you could let W be 16, and Ahigh would
be the top 16 bits of A and Alow would be the bottom 16 bits of A.

If you then multiply Alow * Blow and put the result into an
unsigned long, say T1, then the top W bits of that result are the "carry".
So you calculate Ahigh * Blow + Alow * Bhigh + (T1>>W) and that
gives you the next chunk of bits over -- except you have to
account for carries along the way. Say the result is in T2, then
the "low" unsigned long of the multiplication is
(T2 & ~(1L<<W)) << W | ((T1 & ~(1L<<W))

and so on, just making sure you take into account the carries at
each point. As long as the number of bits at a time that you operate
on does not exceed half the number of bits in an unsigned long,
then the result will always fit within an unsigned long, with the
top bits of that being the carry over to the next stage.
How will you counter in case overflow happens for Ahigh * Blow + Alow *
Bhigh + (T1>>W) ? Over flow status flag must also be taken into
account.

-N

Sep 8 '06 #17
Eric Sosman wrote:
[...]
However, all these conversions, no matter how accurate an
approximation you use, must eventually express the result as a
whole number of gallons or liters. [...]
Not if I use some number of the least significant digits as a
"fractional " part. As you say the value is effectively in something
like milliliters. Thanks.

Sep 8 '06 #18

ga*****@hotmail .com wrote:
I need to do just a few multiplies of long integers and have a divide
by ten. Can I avoid using floats? Can I use two longs as a 64 bit value
somehow? Thanks.
/*
An integral version will work OK if the quantities are huge, but breaks
down badly for small quantities.
*/

long gallons_to_lite rs(long gallons)
{
static const long long numerator = 31754337;
static const long long denominator = 8388608;
return (long) ((gallons * numerator) / denominator);
}

long liters_to_gallo ns(long liters)
{
static const long long numerator = 8388608;
static const long long denominator = 31754337;
return (long) ((liters * numerator) / denominator);
}

double g2l(double gallons)
{
return 3.785412 * gallons;
}

double l2g(double gallons)
{
return gallons / 3.785412;
}

#ifdef UNIT_TEST

#include <stdio.h>
#include <stdlib.h>

static char string[32767];
int main(void)
{
long gallons;
long liters;
puts("Enter gallons:");
fflush(stdout);
fgets(string, sizeof string, stdin);
gallons = atol(string);
printf("%ld gallons_to_lite rs = %ld liters\n", gallons,
gallons_to_lite rs(gallons));
printf("%ld g2l = %g liters\n", gallons,
g2l(gallons));

puts("Enter liters:");
fflush(stdout);
fgets(string, sizeof string, stdin);
liters = atol(string);
printf("%ld liters_to_gallo ns = %ld gallons\n", liters,
liters_to_gallo ns(liters));
printf("%ld l2g = %g gallons\n", liters,
l2g(liters));

return 0;
}
/*
C:\tmp>g2l2c
Enter gallons:
98765
98765 gallons_to_lite rs = 373866 liters
98765 g2l = 373866 liters
Enter liters:
373866
373866 liters_to_gallo ns = 98764 gallons
373866 l2g = 98764.9 gallons

C:\tmp>g2l2c
Enter gallons:
3
3 gallons_to_lite rs = 11 liters
3 g2l = 11.3562 liters
Enter liters:
11
11 liters_to_gallo ns = 2 gallons
11 l2g = 2.90589 gallons

C:\tmp>g2l2c
Enter gallons:
1
1 gallons_to_lite rs = 3 liters
1 g2l = 3.78541 liters
Enter liters:
3
3 liters_to_gallo ns = 0 gallons
3 l2g = 0.792516 gallons

*/
#endif

Sep 8 '06 #19
dc*****@connx.c om writes:
ga*****@hotmail .com wrote:
>I need to do just a few multiplies of long integers and have a divide
by ten. Can I avoid using floats? Can I use two longs as a 64 bit value
somehow? Thanks.

/*
An integral version will work OK if the quantities are huge, but breaks
down badly for small quantities.
*/
You can sometimes get decent results using fixed-point arithmetic. C
doesn't directly support this but you can, for example, use an integer
to represent a number of microliters or nanoliters.

Or you can just use floating-point, and the performance and precision
will probably be perfectly acceptable.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Sep 8 '06 #20

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

Similar topics

1
4331
by: Generale Cluster | last post by:
hello, I've made a template which has the layout I want, but there is an undesired white space between the left elements and the right column. How can I remove it? Thank you Bye!! Here's the code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
4
1737
by: Daniel Mitchell | last post by:
I'm interested in computational physics and have defined an abstract base class to represent a simulation. Now I want to develop a GUI for setting the member data of classes derived from my base class. I've approached this problem by creating a class named Interface with an overloaded member function named addParameter(): class Interface { public: void addParameter( int& param );
3
2746
by: benben | last post by:
Is there a standard guidline to avoid or minimize page faults when manipulating data collections in C++? ben
14
9819
by: wane | last post by:
Hello, I have heard that one should avoid using float and double in monetary calculation because of the lack of preciseness. What is a good alternative? Thanks
4
3641
by: Frank-René Schäfer | last post by:
-- A class needs to have N members according to N types mentioned in a typelist (possibly with one type occuring more than once). -- The classes should be generated **avoiding** multiple inheritance (avoiding prosperation of virtual func tables). -- At the same time, a class taking N types shall contain a virtual member function that calls a function according to the number of arguments That means, something like:
14
3027
by: mast2as | last post by:
Hi everyone, I am trying to implement some specs which specify that an array of parameter is passed to a function as a pointer to an array terminated by a NULL chatacter. That seemed fairly easy to implement. I had a special Malloc function that would allocated the number of needed bytes for the objects i needed to store + 1 additional byte to save the NULL character /*!
2
1546
by: MiG | last post by:
Hello, I have the following operators declared in a class: // Provides R/W direct access to the matrix. __forceinline const T& operator(USHORT ndx) const throw() { _ASSERT(ndx < 16); return(_mx); } __forceinline T& operator(USHORT ndx) throw() { _ASSERT(ndx < 16); return(_mx); }
2
1739
by: David Schwartz | last post by:
I'm trying to learn how to use CSS rather than burdening my code with lots of tables. I've got content that I would normally place in a one row, 3 column table. How to I do this using css instead? The following doesn't work nor does moving the various inner div's around <div width="100%"> <div style="float:right">1111</div> <div style="float:right">2222</div>
0
9511
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
10195
jinu1996
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...
0
9979
tracyyun
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...
0
9016
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
7525
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
6765
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();...
1
4090
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
3695
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2906
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.