473,789 Members | 2,694 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
dc*****@connx.c om 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.

/*
An integral version will work OK if the quantities are huge, but
breaks down badly for small quantities.
*/
To use the ratapprx program I published here earlier, I suggest the
following (untested) routine for the OP.

/* File mulrat.c */
#include "mulrat.h"

/* multiply an integral value by a rational fraction */
/* returns rounded product, -1 for overflow */
long int mulrat(long int value, /* to be processed */
const int num, /* numerator */
const int denom) /* denominator */
{
if (LONG_MAX / num < value + denom / 2) {
/* calculation will overflow */
return -1;
}
return ((value + denom/2) * num) / denom;
} /* mulrat */
/* File mulrat.h */
#ifndef H_mulrat_h
# ifdef __cplusplus
extern "C" {
# endif

#include <limits.h>

/* multiply an integral value by a rational fraction */
/* returns rounded product, -1 for overflow */
long int mulrat(long int value, /* to be processed */
const int num, /* numerator */
const int denom); /* denominator */

# ifdef __cplusplus
}
# endif
#endif

I repeat, untested code.

--
"The smaller aperture of the lid has been designed to prevent
hedgehogs from entering the McFlurry container in the
unfortunate incidence that the lid is littered"
-- McDonalds, as quoted in Time, 2006-09-11

Sep 8 '06 #21

Eric Sosman wrote:
ga*****@hotmail .com wrote On 09/07/06 13:53,:
Konstantin Miller wrote:
>ga*****@hotmai l.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.

Have you considered

long liters, gallons;
liters = ...whatever...;
gallons = liters * 3 / 10;

"Times three, over ten" is a crude approximation to 0.2641721,
but it's the only one I can think of that satisfies your desire
to divide by ten. If you're willing to consider other divisors,
more accurate conversions are possible:

gallons = liters * 26 / 100;
gallons = liters * 264 / 1000;
gallons = liters * 2642 / 10000;
...
picking something that is a power of two might be smart ;)

makes the division simple and also makes it easy to add up
fractions if you need to.

-Lasse

Sep 8 '06 #22
Keith Thompson wrote:
dc*****@connx.c om writes:
>>ga*****@hotma il.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.
This is the solution I have used on a number of embedded control
applications where floating point requires expensive library calls.
Pick the accuracy you require and the minimum sized integer that gives
you adequate headroom and scale the values appropriately.

In most of my applications, the inputs have been analogue voltages,
currents and temperatures where milli-whatevers have been accurate
enough for the application.
Or you can just use floating-point, and the performance and precision
will probably be perfectly acceptable.
Assuming an FPU.

--
Ian Collins.
Sep 8 '06 #23
In article <od************ *************** ***@comcast.com Joe Wright <jo********@com cast.netwrites:
ga*****@hotmail .com wrote:
....
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..
Let's see. 1 US gallon is 231 cubic inches. 1 inch is 2.54 cm.
1000 cubic cm is 1 liter. So 1 (US) gallon is 3.785411784 liter
exactly. And 1 UK gallon is 4.54609 liter exactly. So converting
liters to gallons can not be done with only division by 10, but it
can be done the other way around. (This is all according to the
latest standards.)

But let me see:
One survey foot = 0.3048006096 meters.
1200 / 3937 exactly.
One statute mile = 1.6093472187 kilometers.
6336 / 3937 exactly.
One cubic foot = 7.48051948 US gallons.
1728 / 231 exactly.
One US gallon = 3.785411784 liters (exactly).
Indeed.
One ounce (fluid) = 29.573529562 milliliters.
29.5735295625 ml (473176473 / 16000000) exactly (for the US fluid ounce)
28.4130625 ml (454609 / 16000) exactly (for the UK fluid ounce)
Doing stuff like this without floating point is something I don't want
to even think about.
The conversion factors are all plain rational numbers. In the US that
is the case since 1866 and in the UK since 1995. So doing this with
integer operations only is very viable. (Yes, 1866 was not an error.)
The difference in the US between the survey foot and the standard foot
comes because originally (1866) the US linked the foot to the meter
by a reverse factor to that introduced in 1963. The original foot
remained in use in surveying. Something similar did happen with the
US pound, but here the original pound is no longer used (1 kg =
2.2046 lb in 1866, in 1893 adapted to 2.20462 and in 1894 to 2.20462234).
In 1959 changed to the current definition that was also adopted in the
UK in 1963.

But *all* measures in the US are tightly linked, through rational
conversion factors, to the metric system since 1866.
--
dik t. winter, cwi, kruislaan 413, 1098 sj amsterdam, nederland, +31205924131
home: bovenover 215, 1025 jn amsterdam, nederland; http://www.cwi.nl/~dik/
Sep 9 '06 #24
Dik T. Winter wrote:
In article <od************ *************** ***@comcast.com Joe Wright <jo********@com cast.netwrites:
ga*****@hotmail .com wrote:
...
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..

Let's see. 1 US gallon is 231 cubic inches. 1 inch is 2.54 cm.
1000 cubic cm is 1 liter. So 1 (US) gallon is 3.785411784 liter
exactly. And 1 UK gallon is 4.54609 liter exactly. So converting
liters to gallons can not be done with only division by 10, but it
can be done the other way around. (This is all according to the
latest standards.)

But let me see:
One survey foot = 0.3048006096 meters.

1200 / 3937 exactly.
One statute mile = 1.6093472187 kilometers.

6336 / 3937 exactly.
One cubic foot = 7.48051948 US gallons.

1728 / 231 exactly.
One US gallon = 3.785411784 liters (exactly).

Indeed.
One ounce (fluid) = 29.573529562 milliliters.

29.5735295625 ml (473176473 / 16000000) exactly (for the US fluid ounce)
28.4130625 ml (454609 / 16000) exactly (for the UK fluid ounce)
Doing stuff like this without floating point is something I don't want
to even think about.

The conversion factors are all plain rational numbers. In the US that
is the case since 1866 and in the UK since 1995. So doing this with
integer operations only is very viable. (Yes, 1866 was not an error.)
The difference in the US between the survey foot and the standard foot
comes because originally (1866) the US linked the foot to the meter
by a reverse factor to that introduced in 1963. The original foot
remained in use in surveying. Something similar did happen with the
US pound, but here the original pound is no longer used (1 kg =
2.2046 lb in 1866, in 1893 adapted to 2.20462 and in 1894 to 2.20462234).
In 1959 changed to the current definition that was also adopted in the
UK in 1963.

But *all* measures in the US are tightly linked, through rational
conversion factors, to the metric system since 1866.
All this is trivial, I know, but I remain fascinated.

Using your UK ounce and multiplying by 160 for a UK gallon, I get
4546.09 milliliters. Dividing that by grams per pound gives 10.022412855
pounds per UK gallon. The Imperial Gallon was 10 pounds exactly.

How shall we accommodate this gross inaccuracy? Revisit the
International Standards somehow? :=)

In fun..

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Sep 9 '06 #25
In article <Rp************ *************** ***@comcast.com Joe Wright <jo********@com cast.netwrites:
Dik T. Winter wrote:
....
All this is trivial, I know, but I remain fascinated.
Not so very trivial.
Using your UK ounce and multiplying by 160 for a UK gallon, I get
4546.09 milliliters. Dividing that by grams per pound gives 10.022412855
pounds per UK gallon. The Imperial Gallon was 10 pounds exactly.
It was. Since 1963 it was 10 pounds of water with density 0.998859 gr/ml
weighed in air of density 0.001217 gr/ml against weights of density
8.136 gr/ml. Weights and Measures Bill (G.B.), HC 70 (1963). Now
calculate the volume. Unless I seriously misunderstood Archimedes I
come at 1 gallon = 368987550040571 / 81168153120 ml, or about
4545.96459 ml.

And I think it is; just tweak some of the densities. With the densities
of 1963 I come at 368997729217300 8 / 368987550040571 or about
10.0002758678 pounds. Slightly better than you think, I would say.
Offhand I would not know densities of similar precision that give the
same result, but I think those might exist.
--
dik t. winter, cwi, kruislaan 413, 1098 sj amsterdam, nederland, +31205924131
home: bovenover 215, 1025 jn amsterdam, nederland; http://www.cwi.nl/~dik/
Sep 10 '06 #26
Joe Wright wrote:
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.
I take it you do not write embedded code.
I assume the OP is or why ask the question.
floating point is slow and uses a large chunk of RAM and ROM.
The required accuracy is what fits on the display.
besides even on big iron floating point has it's own issues.
Sep 12 '06 #27
ga*****@hotmail .com wrote:
Eric Sosman wrote:
>[...]
However, all these conversions, no matter how accurate an
approximatio n 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.
A lot of theory here.
If you want a real solution.
The range of liters.
The range of gallons.
The number of significant digits you want to display.
Sep 12 '06 #28

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
9663
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
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,...
1
10136
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,...
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
5415
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...
0
5548
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
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
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.