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

Home Posts Topics Members FAQ

What's the best way to handle this floating point problem?

With this script

<script>
alert(8/(3-8/3))
</script>

I hope to get 24, but I get 23.999999999999 99 in IE 6.0.2800 and
Firefox 1.5.0.4. alert(6/(1-3/4)) returns 24 as expected.

I see a number of threads in this newsgroup about the floating point
issue. It may be hard to get it right. But other languages I tried
don't have this problem with this calculation.

Perl:

C:\>perl -e "print 8/(3-8/3)"
24

Python:

$ python -c 'print 8/(3-8/3.0)' #have to say 3.0, not 3
24.0

Oracle:

SQLselect 8/(3-8/3) from dual;

8/(3-8/3)
----------
24

and awk:

$ awk "BEGIN {print 8/(3-8/3)}"
24

I want to compare the calculation result with 24. What's the best
solution in Javascript? Any advice is appreciated.

Yong Huang

Jul 2 '06 #1
6 2443
yo*****@yahoo.c om wrote:
>
I want to compare the calculation result with 24. What's the best
solution in Javascript? Any advice is appreciated.
You shouldn't compare floating point numbers in any language (unless it
makes some guarantees regarding their accuracy).

The solution is the same as in any other language, compare against a range.

--
Ian Collins.
Jul 2 '06 #2
On Sat, 01 Jul 2006 20:01:11 -0700, yong321 wrote:
With this script

<script>
alert(8/(3-8/3))
</script>

I hope to get 24, but I get 23.999999999999 99 in IE 6.0.2800 and
Firefox 1.5.0.4. alert(6/(1-3/4)) returns 24 as expected.

I see a number of threads in this newsgroup about the floating point
issue. It may be hard to get it right. But other languages I tried
don't have this problem with this calculation.

Perl:

C:\>perl -e "print 8/(3-8/3)"
24

Python:

$ python -c 'print 8/(3-8/3.0)' #have to say 3.0, not 3
24.0

Oracle:

SQLselect 8/(3-8/3) from dual;

8/(3-8/3)
----------
24

and awk:

$ awk "BEGIN {print 8/(3-8/3)}"
24

I want to compare the calculation result with 24. What's the best
solution in Javascript? Any advice is appreciated.

Yong Huang
I would guess that in most of those examples the answer
is silently changed to an integer for you. I'm sure that
I won't be the only one to say "Don't do an exact compare
of floating point numbers" and refer you to the wonderful
work of David Goldberg: (Google for it.)
What Every Computer Scientist Should Know About
Floating-Point Arithmetic

Your options are:
a) Convert it to an integer
b) Compare to a range (if (a-b) < 0.001 then close enough)
c) Rely on how one particular browser happens to handle
floating point numbers and then curse and swear when the
next version of that browser comes out.
Jul 2 '06 #3
yo*****@yahoo.c om wrote:
With this script
alert(8/(3-8/3))

I hope to get 24, but I get 23.999999999999 99 in IE 6.0.2800 and
Firefox 1.5.0.4. alert(6/(1-3/4)) returns 24 as expected.

I see a number of threads in this newsgroup about the floating point
issue. It may be hard to get it right. But other languages I tried
don't have this problem with this calculation.
$ python -c 'print 8/(3-8/3.0)' #have to say 3.0, not 3
24.0
The printed value is somewhat rounded:
>>a = 8/(3-8/3.0)
print a
24.0
>>a == 24
False
>>a-24
-1.0658141036401 503e-014

I expect this is also the case with other languages you've tried. See others' answers for
possible solutions.
Jul 2 '06 #4
Mitja Trampus wrote:
yo*****@yahoo.c om wrote:
With this script
alert(8/(3-8/3))

I hope to get 24, but I get 23.999999999999 99 in IE 6.0.2800 and
Firefox 1.5.0.4. alert(6/(1-3/4)) returns 24 as expected.

I see a number of threads in this newsgroup about the floating point
issue. It may be hard to get it right. But other languages I tried
don't have this problem with this calculation.
$ python -c 'print 8/(3-8/3.0)' #have to say 3.0, not 3
24.0

The printed value is somewhat rounded:
>>a = 8/(3-8/3.0)
>>print a
24.0
>>a == 24
False
>>a-24
-1.0658141036401 503e-014

I expect this is also the case with other languages you've tried. See others' answers for
possible solutions.
Thanks, Mitja. You're right. See this.

Oracle SQL:

SQLselect decode(8/(3-8/3), 24, 'equals', 'not equals') from dual;

DECODE(8/(
----------
not equals

awk:

C:\>gawk "BEGIN {if (8/(3-8/3)!=24) {print \"not equals\"}}"
not equals

C:\>gawk "BEGIN {print 24 - 8/(3-8/3)}"
1.06581e-014

I think that's enough. I'll take the suggestion to compare with a very
small range. Thanks, everyone.

Yong Huang

Jul 2 '06 #5
JRS: In article <11************ **********@m73g 2000cwd.googleg roups.com>,
dated Sat, 1 Jul 2006 20:01:11 remote, seen in news:comp.lang. javascript,
yo*****@yahoo.c om posted :
><script>
alert(8/(3-8/3))
</script>

I hope to get 24, but I get 23.999999999999 99 in IE 6.0.2800 and
Firefox 1.5.0.4. alert(6/(1-3/4)) returns 24 as expected.

Where possible, calculations should be adapted so that all values are
integers multiplied by a not-too-big +- power of 2. You will find no
trouble with alert(8*3/(3*3-8)) ; your second calculation uses only
exact numbers. Please do not start a sentence with a lower-case letter,
since it can lead to confusion; there's always some alternative, such as
inserting the word "And".

Read the newsgroup FAQ (which you should have done before posting), and
my js-round.htm /ff./; via sig below.

If Firefox shows "false" for alert( (8/(3-8/3)) == 24 ) - and that is
IMHO what it should show - then it is deceitfully misrepresenting the
number 23.999999999999 99 as a displayed string '24'.
--
John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4
<URL:http://www.jibbering.c om/faq/>? JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htmjscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 2 '06 #6
JRS: In article <4g************ *@individual.ne t>, dated Sun, 2 Jul 2006
15:17:12 remote, seen in news:comp.lang. javascript, Ian Collins <ian-
ne**@hotmail.co mposted :
>yo*****@yahoo. com wrote:
>>
I want to compare the calculation result with 24. What's the best
solution in Javascript? Any advice is appreciated.
You shouldn't compare floating point numbers in any language (unless it
makes some guarantees regarding their accuracy).
All javascript numbers are floating-point, except maybe in future
versions. So you are actually saying that one should never use
relational operators between javascript Numbers.
In any language, it is reasonable to compare floating-point numbers with
= < <= but not with == or != (in javascript notation). It is also
reasonable to compare for equality floats that are certain to have
integer values (more strictly - that are certain to have exact values).
It is not appropriate to compare for equality a javascript float which
has been calculated by inexact arithmetic, and that means where any
number involved is not of the form of a 53-bit binary integer times two-
to-the-N for N less than about 1024.
--
John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4
<URL:http://www.jibbering.c om/faq/>? JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htmjscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 2 '06 #7

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

Similar topics

2
1425
by: Pekka Henttonen | last post by:
Forgive me this stupid question, but what is the best way to store the length of an object in a database? What datatype would you use? Would it be better to define one of your own?
10
1853
by: John | last post by:
Hi all... Either I'm doing really something really stupid - or maybe there is some bug somewhere (optimizing?). In a function I have: int x1, y1, x2, y2; float dR, dX, dY; dR = (state.cam1x - x1) - (state.cam2x - x2); dX = 0.5 * ((state.cam1x - x1) + (state.cam2x - x2));
24
2264
by: j0mbolar | last post by:
C supports single precision floating point and double precision floating point but does it support fixed floating point? i've read that fixed floating point is more accurate than single precision floating point when dealing with dollars and cents.
10
2274
by: Shawn | last post by:
Hello all, I apologize as I am sure this has probably been dealth with before... but I am doing an exercise from "Practical C Programming" and I have been unable to get it to work perfectly due to problems with floating point arithmetic and I am looking for a way to solve it. See the code below... Given a certain amount of change (below $1.00) the program will tell you how many of each coin you will need to get that amount. The program...
51
4574
by: jacob navia | last post by:
I would like to add at the beginning of the C tutorial I am writing a short blurb about what "types" are. I came up with the following text. Please can you comment? Did I miss something? Is there something wrong in there? -------------------------------------------------------------------- Types A type is a definition for a sequence of storage bits. It gives the meaning of the data stored in memory. If we say that the object a is an
13
5063
by: Jason Huang | last post by:
Hi, Would someone explain the following coding more detail for me? What's the ( ) for? CurrentText = (TextBox)e.Item.Cells.Controls; Thanks. Jason
32
4123
by: ma740988 | last post by:
template <class T> inline bool isEqual( const T& a, const T& b, const T epsilon = std::numeric_limits<T>::epsilon() ) { const T diff = a - b; return ( diff <= epsilon ) && ( diff >= -epsilon ); } int main() { std::deque<double> pt ;
669
26261
by: Xah Lee | last post by:
in March, i posted a essay “What is Expressiveness in a Computer Language”, archived at: http://xahlee.org/perl-python/what_is_expresiveness.html I was informed then that there is a academic paper written on this subject. On the Expressive Power of Programming Languages, by Matthias Felleisen, 1990. http://www.ccs.neu.edu/home/cobbe/pl-seminar-jr/notes/2003-sep-26/expressive-slides.pdf
12
1796
by: EvilOldGit | last post by:
In Stroustrup he talks of a MathErr class that you can use to catch floating point exceptions. It doesn't exist, at least not in Visual C++ I can catch FP exceptions using catch(...) but am stumped in finding out what the class I'm catching is. I would like to know how to catch them in a more elegant way than catch(...) and then poling around in registers to guess the problem. TIA
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, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
9579
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
10330
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
10319
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
10076
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...
1
7616
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
6851
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
5520
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...
3
2990
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.