Rounding fraction values?

T

Tuxedo

Does anyone know how to round up fraction values in Javascript?

I would like to modify a variable starting at 1 ending at 0 in 25
iterations, using setInterval, updating the variable accordingly. In other
words that should be 4% each step. If each interval runs every 50
milliseconds it should take about 1.25 seconds to complete the cycle.

interval = setInterval("change()",50);

1.00 <!- starting value

0.96 first iteration
0.92 second ...
0.88 third ..
0.84 etc.
0.80
0.76
0.72
0.68
0.64
0.60
0.56
0.52
0.48
0.44
0.40
0.36
0.32
0.28
0.24
0.20
0.16
0.12
0.08
0.04
0.00 <- end value and clearInterval(interval)

However, except for the first iteration, simply subtracting 0.04 from each
value will return nemeric values as follows:

0.96
0.9199999999999999
0.8799999999999999
0.8399999999999999
0.7999999999999998
0.7599999999999998
0.7199999999999998
0.6799999999999997
0.6399999999999997
0.5999999999999996
0.5599999999999996
0.5199999999999996
0.4799999999999996
0.4399999999999996
0.39999999999999963
0.35999999999999965
0.3199999999999997
0.2799999999999997
0.23999999999999969
0.19999999999999968
0.15999999999999967
0.11999999999999966
0.07999999999999965
0.039999999999999654
-3.469446951953614e-16

Any ideas? Thanks in advance!
 
T

Tom Cole

Tuxedo said:
Does anyone know how to round up fraction values in Javascript?

I would like to modify a variable starting at 1 ending at 0 in 25
iterations, using setInterval, updating the variable accordingly. In other
words that should be 4% each step. If each interval runs every 50
milliseconds it should take about 1.25 seconds to complete the cycle.

interval = setInterval("change()",50);

1.00 <!- starting value

0.96 first iteration
0.92 second ...
0.88 third ..
0.84 etc.
0.80
0.76
0.72
0.68
0.64
0.60
0.56
0.52
0.48
0.44
0.40
0.36
0.32
0.28
0.24
0.20
0.16
0.12
0.08
0.04
0.00 <- end value and clearInterval(interval)

However, except for the first iteration, simply subtracting 0.04 from each
value will return nemeric values as follows:

0.96
0.9199999999999999
0.8799999999999999
0.8399999999999999
0.7999999999999998
0.7599999999999998
0.7199999999999998
0.6799999999999997
0.6399999999999997
0.5999999999999996
0.5599999999999996
0.5199999999999996
0.4799999999999996
0.4399999999999996
0.39999999999999963
0.35999999999999965
0.3199999999999997
0.2799999999999997
0.23999999999999969
0.19999999999999968
0.15999999999999967
0.11999999999999966
0.07999999999999965
0.039999999999999654
-3.469446951953614e-16

Any ideas? Thanks in advance!

I don't know if this is the perfect solution but have you tried using
something like value = ((value * 100) - 4) / 100 ?
 
L

Lee

Tuxedo said:
Does anyone know how to round up fraction values in Javascript?
0.11999999999999966
0.07999999999999965
0.039999999999999654
-3.469446951953614e-16

Any ideas? Thanks in advance!

This newsgroup, like most technical groups, has a FAQ that should be read
before you ask questions.

The parts you might find particularly interesting are:

http://www.jibbering.com/faq/#FAQ4_6
http://www.jibbering.com/faq/#FAQ4_7

as well as the web pages that those entries refer to, such as:
http://www.merlyn.demon.co.uk/js-round.htm


--
 
V

VK

I would like to modify a variable starting at 1 ending at 0 in 25
iterations, using setInterval, updating the variable accordingly.

So the procedure will consist of subtracting 0.04 from current values.
0.04 == 4/100 == 1/25 == non-diadic fraction
So neither minuend (after first cycle) nor subtrahend (from the
beginning) will not be represented exactly involving internal rounding
and precision loss on each cycle. With 25 cycles the task is way
beyond of IEEE-754 math capabilities - after all it was made for
"home" (PC) math, so you suppose to go easy on it ;-) That is not some
JavaScript-particular limitation, the same apply for any lightweight
PC environment no matter if it's C, C++, C#, Java etc.

Because no one of intermediary values seems fail on equipoint choice
("5 to 1 or 0" in decimal system) you may disregard toFixed rounding
algorithm difference on IE and other browsers so use result.toFixed(2)
after each iteration.

If each interval runs every 50
milliseconds it should take about 1.25 seconds to complete the cycle.

I wouldn't count on it too much. The smallest interval cannot be
smaller than one system tick which is from 10ms to 60ms depending on
OS - with exact IRQ treatment taken very freely for really small
values - I mean on the system level. This way the second sign after
comma is a dangerous bogus - it may make you think that the error
begins from the third sign only. Let's say "it should take lesser than
2 seconds to complete the cycle".
 
D

Dr J R Stockton

In comp.lang.javascript message said:
I would like to modify a variable starting at 1 ending at 0 in 25
iterations, using setInterval, updating the variable accordingly. In other
words that should be 4% each step. If each interval runs every 50
milliseconds it should take about 1.25 seconds to complete the cycle.


You should do as much as possible in integers, as in

for (J=100 ; J>=0 ; J -= 4) { X = J/100 // not J*0.01
... // using X
}

For an understanding of numerical accuracy in javascript, see FAQ 4.7,
IEEE 754, and <URL:http://www.merlyn.demon.co.uk/js-maths.htm>, etc.

It's a good idea to read the newsgroup and its FAQ. See below.
 
T

Tuxedo

T

Tuxedo

VK said:
So the procedure will consist of subtracting 0.04 from current values.
0.04 == 4/100 == 1/25 == non-diadic fraction
So neither minuend (after first cycle) nor subtrahend (from the
beginning) will not be represented exactly involving internal rounding
and precision loss on each cycle. With 25 cycles the task is way
beyond of IEEE-754 math capabilities - after all it was made for
"home" (PC) math, so you suppose to go easy on it ;-) That is not some
JavaScript-particular limitation, the same apply for any lightweight
PC environment no matter if it's C, C++, C#, Java etc.

Because no one of intermediary values seems fail on equipoint choice
("5 to 1 or 0" in decimal system) you may disregard toFixed rounding
algorithm difference on IE and other browsers so use result.toFixed(2)
after each iteration.



I wouldn't count on it too much. The smallest interval cannot be
smaller than one system tick which is from 10ms to 60ms depending on
OS - with exact IRQ treatment taken very freely for really small
values - I mean on the system level. This way the second sign after
comma is a dangerous bogus - it may make you think that the error
begins from the third sign only. Let's say "it should take lesser than
2 seconds to complete the cycle".

I realise processing time will increase the calculation somewhat, but using
setInterval should at least come a bit closer to target than if using
setTimeout for example.

Thanks for all other comments, it gives me a general idea of the
limitations and complexity....
 
T

Tuxedo

Dr said:
You should do as much as possible in integers, as in

for (J=100 ; J>=0 ; J -= 4) { X = J/100 // not J*0.01
... // using X
}

For an understanding of numerical accuracy in javascript, see FAQ 4.7,
IEEE 754, and <URL:http://www.merlyn.demon.co.uk/js-maths.htm>, etc.

It's a good idea to read the newsgroup and its FAQ. See below.

Many thanks for the above tips!
 
R

Richard Cornford

Does anyone know how to round up fraction values in Javascript?

I would like to modify a variable starting at 1 ending at 0 in 25
iterations, using setInterval, updating the variable accordingly. In other
words that should be 4% each step. If each interval runs every 50
milliseconds it should take about 1.25 seconds to complete the cycle.

interval = setInterval("change()",50);

1.00 <!- starting value

0.96 first iteration
0.92 second ...
0.88 third ..
0.84 etc.
0.04
0.00 <- end value and clearInterval(interval)

However, except for the first iteration, simply subtracting 0.04
from each value will return nemeric values as follows:

0.96
0.9199999999999999
0.039999999999999654
-3.469446951953614e-16

Any ideas? Thanks in advance!

The thing that you have not explained is why. You are trying to
achieve something, and the fact that what you are trying to achieve
will not work the way you are trying it does not mean that it cannot
be achieved in some other way.

Richard.
 
D

Dr J R Stockton

Thu said:
Tuxedo said:
This newsgroup, like most technical groups, has a FAQ that should be read
before you ask questions.

The parts you might find particularly interesting are:
as well as the web pages that those entries refer to, such as:
http://www.merlyn.demon.co.uk/js-round.htm

Strictly, what you write is correct. But not in detail helpful,
since fundamentally he should not be using rounding, and should be
reading js-maths.htm
 
V

VK

VK wrote:

a load of crap

Poor child,
which one of your darling illusions did I break? I cannot change the
world but at least I could bring some addressed consolations for you.
 
R

Randy Webb

VK said the following on 2/23/2007 11:15 AM:
Poor child,
which one of your darling illusions did I break?

The illusion that you had an IQ above 10 would be a start.
 
V

VK

I realise processing time will increase the calculation somewhat, but using
setInterval should at least come a bit closer to target than if using
setTimeout for example.

Two wrong assumptions in here:

1) the lateness of setTimeout/setInterval is rarely affected by the
complexity of calculations, at least definitely not in your case. I
cannot imagine an environment where calculating 1-0.04 = ? would take
50,000,000 or more processor cycles (taking 1GHz processor for the
start and 50ms as timeframe).
The problem is not when the process is ended: the problem is when the
process is started. setTimeout/setInterval are working on IRQ
(Interruption ReQuest) principles where everything is based on request
priority. When the system gets several different requests at one time,
it decides by their priorities what to proceed with and what to put on
hold till the next tick. setTimeout/setInterval IRQs from javascript
engine have the lowest priority. So every time the system has a
request to say move your DIV 1px right and anything else more
important to do (refresh screen, close file, handle swap file etc.
etc.) your IRQ is put on hold - because unlike other tasks this one
doesn't menace the system stability.

2) setTimeout and setInterval have the same IRQ priority, no any
advantages. The danger of setInterval is that with persistent lateness
you can get "on hold queue" growing and growing with many undesirable
effects. This is why I would never use setInterval for anything except
some simple operations with predictable execution time, like some
simple clock on the screen.

Netscape 4.0 and inherited by Gecko-based browsers do send extra
argument on timed call indicating lateness of the timeout in
milliseconds. It is called "lateness" but in fact IRQ can be processed
earlier as well if the system has some time left in the current tick
so do not waste it. This is why I said "taken very freely". So the
proper term would be "timeout delta value".

Some code to play with if still interested (Firefox or other Gecko-
based browser needed). It displays
processed number | timeout delta


<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
<script>
var num = 1;

var out = null;

function init() {
out = document.getElementById('output');
counter();
}

function counter() {
out.appendChild(document.createElement('li')).
appendChild(document.createTextNode(num.toFixed(2).
concat(' | ', arguments[0])));
if (num >= 0.04) {
num = (num-0.04);
window.setTimeout(counter, 50);
}
}

window.onload = init;
</script>
</head>

<body>
<ol id="output">
</ol>
</body>
</html>
 
V

VK

Thanks for all other comments

This is what I forgot to mention the first time. That is just a
suggestion: If one makes a new post in hope to get some responses then
X-No-Archive header is a rather bad idea. I understand that some
people may be overly shy :) or considering their questions as of too
low of relevance. Still X-No-Archive header should be used only in
particular circumstances like say announcements of dated events and
advertisement. Otherwise on news servers with X-No-Archive support
(Google archiver is one of them) it creates broken threads "coming
from nowhere" or with responses addressed to "nowhere".
 
D

Dr J R Stockton

In comp.lang.javascript message <[email protected]
1) the lateness of setTimeout/setInterval is rarely affected by the
complexity of calculations, at least definitely not in your case. I
cannot imagine an environment where calculating 1-0.04 = ? would take
50,000,000 or more processor cycles (taking 1GHz processor for the
start and 50ms as timeframe).
The problem is not when the process is ended: the problem is when the
process is started. setTimeout/setInterval are working on IRQ
(Interruption ReQuest) principles where everything is based on request
priority. When the system gets several different requests at one time,
it decides by their priorities what to proceed with and what to put on
hold till the next tick.


That would be a ludicrous way to build a system; I am surprised that
even you might suggest it.

The sensible way is to have a queue of events, ordered by the time when
it is desired that they should occur.

When a tick occurs, the events for that tick are started or performed in
turn, in priority order (they should probably be listed in that order,
for swift dispatch). Hopefully, all will be dealt with before the next
tick; if not, a higher-priority one which has become due will interrupt
a lower-priority one.

The system must have a policy to handle the case where the average
amount of work demanded exceeds what can be done in the time available.

It's a good idea to read the newsgroup and its FAQ. See below.
 
T

Tuxedo

VK wrote:

[..]
X-No-Archive header is a rather bad idea. I understand that some

This is or was a default setting of the newsreader used, which I was
unaware of as I do not keep full headers on display.

[...]
advertisement. Otherwise on news servers with X-No-Archive support

Surprisingly this newsgroups, as many others, appears resistant to
spamvertising. I doubt any spammers would use the X-No-Archive for good
measure.
(Google archiver is one of them) it creates broken threads "coming
from nowhere" or with responses addressed to "nowhere".

True, this can make a thread incomprehensible.
 
T

Tuxedo

VK wrote:

[..]
X-No-Archive header is a rather bad idea. I understand that some

This is or was a default setting of the newsreader used, which I was
unaware of as I do not keep full headers on display.

[...]
advertisement. Otherwise on news servers with X-No-Archive support

Surprisingly this newsgroups, as many others, appears resistant to
spamvertising. I doubt any spammers would use the X-No-Archive for good
measure.
(Google archiver is one of them) it creates broken threads "coming
from nowhere" or with responses addressed to "nowhere".

True, this can make a thread incomprehensible.
 
T

Tuxedo

Randy Webb wrote:

[..]
The illusion that you had an IQ above 10 would be a start.

I'm not sure what the bickering is all about!? I thought this was a
civilized NG ;-)
 
T

Tuxedo

Richard Cornford wrote:

[..]
be achieved in some other way.

It is true that I did not point out "why" in my original post.

The original purpose was simply to generate a sequence of legal opacity
values with a loop. Later however I realized that it probably makes little
or no difference whether fractional or rounded values are used for this, so
the question became more for a point than for a purpose, i.e. how to output
the rounded numbers by some simple math formula, thus I ommited the
purpose. By the various responses above I also realized that this may be
easier said than done, and that I have many faq's to read on this subject.
And as you say, there probably are other ways of achieving the same.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top