473,567 Members | 2,957 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 2425
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
1417
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
1818
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
2215
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
2247
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...
51
4475
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...
13
5023
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
4065
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
25640
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....
12
1777
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...
0
7690
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...
0
7597
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...
0
7909
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7961
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...
0
6273
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...
1
5492
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...
0
3630
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1206
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
930
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...

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.