473,756 Members | 1,823 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Math Problem

How do I add floating point numbers accurately?

The following adds the 4 numbers
46.57, 45.00, 45.00, and 54.83 to give
191.39999999999 998 instead of 191.40.

<html>
<head>
<title>floats.h tm</title>
</head>
<body>
<script type="text/javascript">
var a = [46.57,45.00,45. 00,54.83];
var t = 0.00;
for (var i=0; i<a.length; i++) {
alert(t + "\n" + a[i])
t += a[i];
}
alert(t + " = 191.40 ?")
</script>
</body>
</html>

Thanks in advance.

P.S. This FAQ doesn't help:
http://jibbering.com/faq/#FAQ4
4.7 Why does 5 * 1.015 != 5.075 or 0.05+0.01 != 0.06?
Oct 5 '05 #1
8 2315
McKirahan wrote:
How do I add floating point numbers accurately? Using '+'.

A simpler demonstration of your problem:
alert(136.57+54 .83);
shows 191.39999999999 998

P.S. This FAQ doesn't help:
http://jibbering.com/faq/#FAQ4
4.7 Why does 5 * 1.015 != 5.075 or 0.05+0.01 != 0.06?

It should help. It says:
Javascript numbers are represented in binary as IEEE-754 Doubles, with
a resolution of 53 bits, giving an accuracy of 15-16 decimal digits;
integers up to about 9e15 are precise, but few decimal fractions are.


in this case 136.57 is stored internally as 136.56999999999 999,
54.83 is stored internally as 54.829999999999 998.

Adding these together and reducing the result to the appropriate precision
gives the answer displayed above.

If you want to display a friendlier value as the result, change your final
alert to:
alert(t.toFixed (2) + " = 191.40 ?");
Oct 5 '05 #2
"McKirahan" <Ne**@McKirahan .com> wrote:
How do I add floating point numbers accurately?

The following adds the 4 numbers
46.57, 45.00, 45.00, and 54.83 to give
191.3999999999 9998 instead of 191.40.


That's the way it is. Not all decimal fractions can be represented
exactly as binary fractions, which is how floating point numbers are
stored. Floating point numbers are necessarily somewhat imprecise. In
this case the imprecision is on the order of 10**-12, which is
extremely tiny.

--
Tim Slattery
Sl********@bls. gov
Oct 5 '05 #3
McKirahan wrote:
How do I add floating point numbers accurately?

The following adds the 4 numbers
46.57, 45.00, 45.00, and 54.83 to give
191.39999999999 998 instead of 191.40.

Some variation of the following:
/Math.round(Math .pow(10,x)*(46. 57+45.00+45.00+ 54.83))/Math.pow(10,x);/

Where x equals number of digits required to the right of the decimal point.
Mick
Oct 5 '05 #4
If performance is not an issue you could write some arbitrary precision
mathematics.

I.e. you store a number as an array of digits, and perform long
division, long addition etc.

Oct 5 '05 #5
McKirahan said the following on 10/5/2005 7:44 AM:
How do I add floating point numbers accurately?

The following adds the 4 numbers
46.57, 45.00, 45.00, and 54.83 to give
191.39999999999 998 instead of 191.40.
You convert them to whole numbers, do your math, and then use string
manipulation to put the decimal back where you want it along with
leading and/or trailing zeroes.
P.S. This FAQ doesn't help:
http://jibbering.com/faq/#FAQ4
4.7 Why does 5 * 1.015 != 5.075 or 0.05+0.01 != 0.06?


4.7 along with 4.6 do answer your question, they just aren't very well
worded and/or explained enough to make sense to anybody that doesn't
understand it to start with.

--
Randy
comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly
Oct 5 '05 #6
McKirahan <Ne**@McKirahan .com> wrote in message news:GM******** ************@co mcast.com...
How do I add floating point numbers accurately?

The following adds the 4 numbers
46.57, 45.00, 45.00, and 54.83 to give
191.39999999999 998 instead of 191.40.


If you happen to be handling money, it's preferable to avoid floating point calculations by working in pennies, then
formatting the result.

var pennies=12305

var dollars=Math.fl oor( pennies / 100 ), cents = pennies % 100;

result = dollars + '.' + ((cents < 10) ? ('0' + cents) : cents);

--
S.C.


Oct 5 '05 #7
Tim Slattery wrote:
McKirahan wrote:
How do I add floating point numbers accurately?

The following adds the 4 numbers
46.57, 45.00, 45.00, and 54.83 to give
191.399999999 99998 instead of 191.40.


That's the way it is. Not all decimal fractions can be
represented exactly as binary fractions, which is how
floating point numbers are stored. Floating point numbers
are necessarily somewhat imprecise. In this case the
imprecision is on the order of 10**-12, which is extremely
tiny.


And it isn't a characteristic restricted to binary representations of
numbers. How precise is the decimal fraction representation of 1/3? And
would it be reasonable to complain that 3.33 + 3.33 + 3.33 did not
result in 1?

Richard.
Oct 5 '05 #8
Richard Cornford said the following on 10/5/2005 7:29 PM:
Tim Slattery wrote:
McKirahan wrote:
How do I add floating point numbers accurately?

The following adds the 4 numbers
46.57, 45.00, 45.00, and 54.83 to give
191.39999999 999998 instead of 191.40.


That's the way it is. Not all decimal fractions can be
represented exactly as binary fractions, which is how
floating point numbers are stored. Floating point numbers
are necessarily somewhat imprecise. In this case the
imprecision is on the order of 10**-12, which is extremely
tiny.

And it isn't a characteristic restricted to binary representations of
numbers. How precise is the decimal fraction representation of 1/3? And
would it be reasonable to complain that 3.33 + 3.33 + 3.33 did not
result in 1?


Umm, yes it would since it should either result in 9.99 or 10, not 1 :)

--
Randy
comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly
Oct 6 '05 #9

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

Similar topics

16
2323
by: Frank Millman | last post by:
Hi all I was helping my niece with her trigonometry homework last night. Her calculator's batteries were flat, so I thought I would use Python's math module to calculate sin, cos, and tan. I tried the example in the text book first, to ensure that I was getting the correct result, but it did not agree. Then my wife had the idea of using the Microsoft calculator in scientific mode, and that one did give the correct result.
1
2741
by: limelight | last post by:
I have discovered a math error in the .NET framework's Log function. It returns incorrect results for varying powers of 2 that depend on whether the program is run from within the IDE or from the command line. The amount by which the calculation is off is very small; even though the double data type holds the errant value, it seems to round off when printed (via ToString()) and shows the correct one. The problem is that the errant value is...
1
1867
by: Reiner Apke | last post by:
Hello, I have got a very strange problem with the calcualtion of the the square root (Math.Sqrt()). I calculate in a loop a lot of of diameters maxDiameter = Math.Sqrt(maxCrossSection * 4.00 / Math.PI); minDiameter = Math.Sqrt(minCrossSection * 4.00 / Math.PI);
5
2254
by: Ark | last post by:
Hi everyone, Does anyone know if Direct3D overloads System.Math functions? Also is it possible to access the base functions of the overloaded function (in other words restore original of the overlaoded function)? Thank you
6
7098
by: ng_mr | last post by:
No, not a question about "banker's rounding" or whatever it's called. I want to round a double to the nearest 100th, so I perform the following: // original is a double double result = Math.Round( original, 2 ); But I'm not happy with the results. E.g. if original is
110
8595
by: Gregory Pietsch | last post by:
I'm writing a portable implementation of the C standard library for http://www.clc-wiki.net and I was wondering if someone could check the functions in math.h for sanity/portability/whatever. I'm almost halfway through writing the over 200 functions needed to implement C99's version of math.h, and I would like to have some feedback and/or expert advice on my implementations. Sincerely, Gregory Pietsch
11
7364
by: Sambo | last post by:
I have the following module: ------------------------------- import math def ac_add_a_ph( amp1, ph1, amp2, ph2 ): amp3 = 0.0 ph3 = 0.0 ac1 = ( 0, 0j ) ac2 = ( 0, 0j )
10
16029
by: David Coleman | last post by:
I am running VS 2003 and have applied SP1. (On WinXP SP2, .Net 1.1) In the Command Window I get the following ? Math.Round(0.715, 2) 0.72 ? Math.Round(0.725, 2) 0.72 ? Math.Round(0.735, 2) 0.74
4
10894
by: =?Utf-8?B?UmVuZQ==?= | last post by:
Hello everyone I have a problem with Math.Round, it´s ocurring some strange: Math.Round(12.985) = 12.98, it´s wrong. It should be: 12.99 Why?? What is the problem? Help ME !!!!
17
3921
by: Lenni | last post by:
Hi, I'm currently writing a web application for bicycle wheel builders that calculate the spoke length for all sorts of variations of hubs and rims. I have translated the formula from an Excel spreadsheet and in JavaScript it looks like this: var sll=Math.sqrt(Math.pow(((fdl/2*Math.sin((2*Math.PI*cross)))/
0
9456
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
9275
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
9872
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...
1
9843
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
9713
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
8713
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
7248
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
5304
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3805
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

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.