Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Javascript Math problem

29 views
Skip to first unread message

Tom

unread,
Apr 27, 2012, 6:41:55 PM4/27/12
to
Hi, I was wondering if someone could help me with math puzzle. I need a
function that will give me the number of times an integer is divisible
by 3, but I can't use the round function. In other words,
if I sent the value of 6, it would return 2 since 6/3 = 2. 9/3 = 3 etc.
For numbers that are not evenly divisible, 5/3 would need to return 1,
7/3 would return 2 etc, basically scrap the decimal numbers. But like I
said it can't use round.

I was thinking that possibly it would use some combination of the
division and modulus operators (/,%), but I haven't been able to figure
it out yet.

Can anyone think of anything? Thx

Stefan Weiss

unread,
Apr 27, 2012, 7:33:18 PM4/27/12
to
Math.round() would have been the wrong tool anyway: Math.round(5/3) is
2, not 1. You probably meant Math.floor(): Math.floor(5/3) is 1. Note
that floor() will round in the wrong direction if the quotient is negative.

There are other methods, too:

parseInt(5/3)
~~(5/3)
(5/3) >> 0
(5/3) | 0

By the way, what you are describing is called "integer division".

Out of curiosity, why can't you use round()? Was that part of the
assignment?

- stefan

Michael Haufe (TNO)

unread,
Apr 27, 2012, 8:30:23 PM4/27/12
to
Simple enough for the mathematically inclined:

function f(n){ return (n-(n%3))/3 }

Tom

unread,
Apr 27, 2012, 9:02:58 PM4/27/12
to
Actually its for something I'm doing at work.

I'm using a tool that automatically generates scripts (in html and js)
for taking orders for products. You don't have to be a coder to use it
and I don't normally do this, but it does most of the work for you. You
just basically use templates of screens and tack them together in the
desired flow. For this particular script, the client was giving 1 free
widget with every 3 purchased.

There is a screen in this tool where you can build and test functions
by clicking a button, but for some reason it didn't like round or floor.
So I found myself trying division, modulus and trying to subtract out
the decimal part.

I did come up with a work around, but your solution is much cleaner.
Thanks for the help.

Tom

Tom

unread,
Apr 27, 2012, 9:05:31 PM4/27/12
to
This was exactly what I was trying to do. Dammit I was so close. Thx, Tom

Stefan Weiss

unread,
Apr 27, 2012, 10:00:14 PM4/27/12
to
On 2012-04-28 02:30, Michael Haufe (TNO) wrote:
> Simple enough for the mathematically inclined:
>
> function f(n){ return (n-(n%3))/3 }

Ah yes, I forgot to add that one. I got distracted when I checked how
well the different methods did when the input numbers are not positive
integers. That's not relevant to the OP's question, but I was curious.

I find the behavior of the modulo operator very hard to memorize...
If divisor and dividend aren't both simple positive integers, the
results vary widely across different languages:

In JS, -5.5 % 3 is -2.5 ...

In PHP, -5.5 % 3 is -2 ...

In Python, -5.5 % 3 is 0.5 ...

In Perl, -5.5 % 3 is 1 ...
(unless you "use integer", then it depends on the compiler)

In C, -5.5 % 3 doesn't work at all (int only)...
(but fmod(-5.5, 3) returns -2.5)
(oh, and the behavior with negative numbers is
"implementation defined")

Gaaah!

-stefan

Evertjan.

unread,
Apr 28, 2012, 5:02:43 AM4/28/12
to
I would prefer (given n>=0 for both functions):

function f(n) {return Math.floor(n/3);};

visually simpler (so less bug-prone), and perhaps faster.

--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)

Thomas 'PointedEars' Lahn

unread,
Apr 28, 2012, 7:04:24 AM4/28/12
to
Stefan Weiss wrote:

> On 2012-04-28 02:30, Michael Haufe (TNO) wrote:
>> Simple enough for the mathematically inclined:
>>
>> function f(n){ return (n-(n%3))/3 }
>
> Ah yes, I forgot to add that one.

However, that approach requires three floating-point operations (and one
call of a user-defined function), whereas

Math.floor(n / 3)

only requires two (and one property access and one built-in function call).
ISTM that therefore the cost and potential rounding error is greater with
the former than with the latter, and that the latter should be preferred,
at least for n >= 0.

> […]
> In JS, -5.5 % 3 is -2.5 ...

You mean _in conforming implementations of ECMAScript_, of course.

> In PHP, -5.5 % 3 is -2 ...
>
> In Python, -5.5 % 3 is 0.5 ...
>
> In Perl, -5.5 % 3 is 1 ...
> (unless you "use integer", then it depends on the compiler)
>
> In C, -5.5 % 3 doesn't work at all (int only)...
> (but fmod(-5.5, 3) returns -2.5)
> (oh, and the behavior with negative numbers is
> "implementation defined")

Fascinating.


PointedEars
--
Prototype.js was written by people who don't know javascript for people
who don't know javascript. People who don't know javascript are not
the best source of advice on designing systems that use javascript.
-- Richard Cornford, cljs, <f806at$ail$1$8300...@news.demon.co.uk>

Mel Smith

unread,
Apr 28, 2012, 11:00:09 AM4/28/12
to
Stefan said:
> In JS, -5.5 % 3 is -2.5 ...
>
> In PHP, -5.5 % 3 is -2 ...
>
> In Python, -5.5 % 3 is 0.5 ...
>
> In Perl, -5.5 % 3 is 1 ...
> (unless you "use integer", then it depends on the compiler)
>
> In C, -5.5 % 3 doesn't work at all (int only)...
> (but fmod(-5.5, 3) returns -2.5)
> (oh, and the behavior with negative numbers is
> "implementation defined")
>

Stefan:

... and in my language (xHarbour -- eXtended Harbour: a language that is
compiled into C functions using the old Borland BCC 5.5.1 verion in this
instance), the statement and results are:

nTest := -5.5 % 3
? ntest // result -2.5
? str(nTest) // result -2.5 -- same

-Mel


Stefan Weiss

unread,
Apr 28, 2012, 3:10:18 PM4/28/12
to
On 2012-04-28 13:04, Thomas 'PointedEars' Lahn wrote:
> Stefan Weiss wrote:
>
>> On 2012-04-28 02:30, Michael Haufe (TNO) wrote:
>>> Simple enough for the mathematically inclined:
>>>
>>> function f(n){ return (n-(n%3))/3 }
>>
>> Ah yes, I forgot to add that one.
>
> However, that approach requires three floating-point operations (and one
> call of a user-defined function), whereas
>
> Math.floor(n / 3)
>
> only requires two (and one property access and one built-in function call).
> ISTM that therefore the cost and potential rounding error is greater with
> the former than with the latter, and that the latter should be preferred,
> at least for n >= 0.

I also had the suspicion that rounding could introduce errors here, and
I did a half-hearted search for such a case, but couldn't find one.
Things might get interesting at the 2^32 boundary for bit operations,
and 2^53 for arithmetic operations, but for calculations with numbers of
that magnitude we need to take special precautions anyway.

As for performance, function calls (built-in or user-defined) are
generally much more expensive than numeric operations (unless the
functions are inlined by the compiler). Without testing, I'd expect
(a/b)|0 or (a/b)>>0 to perform best out of the expressions mentioned in
this thread. Math.floor() would still be my choice for the "normal"
case, small positive integers and few repetitions, because the intent of
the code is immediately obvious.

>> In JS, -5.5 % 3 is -2.5 ...
>
> You mean _in conforming implementations of ECMAScript_, of course.

No, Thomas, I don't. Anywhere else, I would have written "JavaScript"
and people would automatically understand it as a pars pro toto. Only in
this group do I write "JS", because up until now, this has spared me
your there-is-no-javascript replies, which I find incredibly tedious.

You are the only person who ever complains about others using
"JavaScript", "Javascript", "javascript", or "JS". It would be nice if
you could get it into your head that people need a catch-all term for
this language and its variants. When there's a relevant distinction to
be made between engines, dialects, or versions, we'll mention it. I'm
certainly not going to write "conforming implementations of ECMAScript"
every time. If you have a better suggestion, please let us hear it. If
you don't, please accept what has become general usage. You're fighting
against windmills here.

- stefan

Thomas 'PointedEars' Lahn

unread,
Apr 28, 2012, 4:23:38 PM4/28/12
to
Stefan Weiss wrote:

> On 2012-04-28 13:04, Thomas 'PointedEars' Lahn wrote:
>> Stefan Weiss wrote:
>>> On 2012-04-28 02:30, Michael Haufe (TNO) wrote:
>>>> Simple enough for the mathematically inclined:
>>>>
>>>> function f(n){ return (n-(n%3))/3 }
>>>
>>> In JS, -5.5 % 3 is -2.5 ...
>>
>> You mean _in conforming implementations of ECMAScript_, of course.
>
> No, Thomas, I don't. Anywhere else, I would have written "JavaScript"
> and people would automatically understand it as a pars pro toto.

No, as you would not have bothered to define the term before using it (the
same as you have not bothered to define "JS"), they too would have acquired
or seen confirmed their common misconception that there was only one
programming language that was implemented everywhere. As a result, they
would not care about the implementations of ECMAScript, and their
differences. Instead they would begin or continue to ascribe well-specified
differences and the differences that must follow from ECMAScript
implementations being only the interface languages to APIs like the DOM to
"JavaScript bugs".

> Only in this group do I write "JS", because up until now, this has spared
> me your there-is-no-javascript replies, which I find incredibly tedious.

Your mistakes are your problems alone.

> You are the only person who ever complains about others using
> "JavaScript", "Javascript", "javascript", or "JS".

No, I am pointing out that this is imprecise, ambiguous, and potentially
confusing terminology that does not do this topic justice. I have also
showed repeatedly and I will continue to show why that is the case. You
just have to pay more attention to that.

> It would be nice if you could get it into your head that people need a
> catch-all term for this language and its variants.

Since JavaScript 1.0 and JScript 1.1 can be considered obsolete, the catch-
all term for the rest of discussions is there: ECMAScript implementations.
It is what the Specification says (in all its Editions), so it describes
these programming languages best. It shows where they are *really* coming
from (JavaScript was the first, but not the only one; JavaScript has evolved
in the meantime, while other implementations have not as much) and it avoids
implying the fallacy that these languages are identical or almost identical.
Because they are _not_.

> When there's a relevant distinction to be made between engines, dialects,
> or versions, we'll mention it.

There are no dialects; that is just another form of the same fallacy. There
are different implementations of a rather loose standard for an extensible
programming language that differ from one another in more than one respect.
The best way to refer to a specific implementation is to use its name, like
JavaScript, JScript and so on. In any other case, it is best to not use
their names in whatever similar spelling or abbreviation, to avoid the
ambiguity, which is bound to cause misunderstandings among and create
misconceptions especially on part of the uninitiated, but certainly the
casual reader.

> I'm certainly not going to write "conforming implementations of
> ECMAScript" every time.

You do not have to. "ECMAScript implementations" usually suffices in a
general discussion.

> If you have a better suggestion, please let us hear it.

Apparently you are thinking that by using the royal "we" you would be more
right or have more rights than if you had just used "I". You should know
that this is a common fallacy (argumentum ad populum). Keep in mind that
wise thought by Bertrand Russell that even if all agree – as construed by
you, which is not necessarily the case – all can still be wrong. And in
this case, though it may be still ignored by many, it has been showed
already. It will be showed again.

> If you don't, please accept what has become general usage. You're fighting
> against windmills here.

Your analogy is flawed. That the majority of people do not know or care
about semantics is not a good reason for the literate to abandon it. That
the majority of people do not know what they are doing is not a good reason
for the knowledgable to give in to a trend of oversimplification. Indeed,
it is especially their respective duty to uphold the long sought and fought
for standards of (technical) discussion so that the world is not going to
end in meaningless babble.

No, we are _not_ discussing "javascript" here; we are discussing ECMAScript
implementations and applications thereof. And, by contrast, *that* "we"
*does* include all active participants, whether they already know it or not.


PointedEars
--
Use any version of Microsoft Frontpage to create your site.
(This won't prevent people from viewing your source, but no one
will want to steal it.)
-- from <http://www.vortex-webdesign.com/help/hidesource.htm> (404-comp.)

Jukka K. Korpela

unread,
Apr 28, 2012, 4:39:41 PM4/28/12
to
2012-04-28 23:23, the resident troll Thomas 'PointedEars' Lahn wrote:

> No, we are _not_ discussing "javascript" here;

That's a useful remainder indeed, especially to newcomers. They, the
troll, are not even claiming to discuss javascript here, in
comp.lang.javascript.

--
Yucca, http://www.cs.tut.fi/~jkorpela/

Stefan Weiss

unread,
Apr 28, 2012, 11:59:09 PM4/28/12
to
On 2012-04-28 22:23, Thomas 'PointedEars' Lahn wrote:
> Stefan Weiss wrote:
>> On 2012-04-28 13:04, Thomas 'PointedEars' Lahn wrote:
>>> You mean _in conforming implementations of ECMAScript_, of course.
>>
>> No, Thomas, I don't. Anywhere else, I would have written "JavaScript"
>> and people would automatically understand it as a pars pro toto.
>
> No, as you would not have bothered to define the term before using it (the
> same as you have not bothered to define "JS"), they too would have acquired
> or seen confirmed their common misconception that there was only one
> programming language that was implemented everywhere. As a result, they
> would not care about the implementations of ECMAScript, and their
> differences. Instead they would begin or continue to ascribe well-specified
> differences and the differences that must follow from ECMAScript
> implementations being only the interface languages to APIs like the DOM to
> "JavaScript bugs".

"You would not"... "they would"... this is all conjecture.
I guess your point here is that using "JavaScript" as an umbrella term
for ECMAScript implementations is harmful to newcomers. I will readily
admit that "ECMAScript implementations" is more correct, but I dispute
that any real harm is being done by using the name "JavaScript" loosely,
or by accepting this usage from someone else. If a person is new to JS,
chances are they've never heard of ECMAScript before. If they're serious
about learning the language, they will find out about it soon enough; if
they aren't serious, it doesn't matter either way. You smugly telling
them that "There is no javascript", without any kind of explanation,
will only confuse and alienate them. And that's why I'm so annoyed by
your constant intentionally cryptic replies in this group. If you really
cared about educating people, you'd give them a polite pointer to a
JS/ES terminology page. Instead you'd rather annoy them (and many of the
regulars) with one of you smartass replies.

>> When there's a relevant distinction to be made between engines, dialects,
>> or versions, we'll mention it.
>
> There are no dialects; that is just another form of the same fallacy.

No, that's just you objecting to a word again. Many others are fine with
"dialects" in this context (use Google to confirm this if you don't
believe me). There's even a whole section on ECMAScript dialects on
Wikipedia.
Whatever... call it "variants", if that makes you happy.

>> I'm certainly not going to write "conforming implementations of
>> ECMAScript" every time.
>
> You do not have to. "ECMAScript implementations" usually suffices in a
> general discussion.

So does "JS", unless you're trying hard very to misunderstand somebody.

>> If you have a better suggestion, please let us hear it.
>
> Apparently you are thinking that by using the royal "we" you would be more
> right or have more rights than if you had just used "I".

Excuse me, but are you insane? "Royal we"? I was asking you to tell the
group your suggestion.
If you're under the impression that I'm the only one who's fed up with
your there-is-no-javascripts, you don't read this group closely enough.

> Keep in mind that wise thought by Bertrand Russell that even if all
> agree – as construed by you, which is not necessarily the case – all
> can still be wrong.

First, I never said anything like that, and you know it. Second, while
it's possible that "everybody" is wrong, that doesn't mean that the lone
Quixote is necessarily right. (And third, if I had quoted Betrand
Russell, no doubt you'd be accusing me of "appeal to authority" now.)

It isn't even a question of right or wrong. I know that JavaScript is,
strictly speaking, the name for one specific implementation, while
"ECMAScript implementations" encompasses all of them. So yes, you're
right about that, no doubt.

Nevertheless, JavaScript has become the term by which browser scripting
in general is now known to the masses. Websites don't ask you to
activate an ECMAScript implementation; when you talk to a client, you
don't say that a form input could be checked with an ECMAScript
implementation; when you create an external script file, you don't name
it ufpdbfrm.es, you name it ufpdbfrm.js. Some insist on using .es, but
.es is not likely to become popular. ECMAScript was always an unwanted
trade name that sounds like a skin disease.

Face it, this boat has sailed. When a name becomes popular enough, it
can become too powerful to dislodge, even if a more correct name exists.
People now google things on Bing, and you yourself have no problem
calling your current OS Linux, when the "more correct" name would be
GNU/Linux. These things happen all the time, and it's fine, until
somebody comes along and tries to find ambiguities where none exist.

> No, we are _not_ discussing "javascript" here; we are discussing ECMAScript
> implementations and applications thereof.

I say that we do both. If names are so important to you, then by all
means use the one you prefer. But when you talk to other people, you
should consider following Postel's Law: be liberal in what you accept
from others, and conservative in what you yourself write.

- stefan

Thomas 'PointedEars' Lahn

unread,
Apr 29, 2012, 10:15:54 AM4/29/12
to
Stefan Weiss wrote:

> On 2012-04-28 22:23, Thomas 'PointedEars' Lahn wrote:
>> Stefan Weiss wrote:
>>> On 2012-04-28 13:04, Thomas 'PointedEars' Lahn wrote:
>>>> You mean _in conforming implementations of ECMAScript_, of course.
>>> No, Thomas, I don't. Anywhere else, I would have written "JavaScript"
>>> and people would automatically understand it as a pars pro toto.
>>
>> No, as you would not have bothered to define the term before using it
>> (the same as you have not bothered to define "JS"), they too would have
>> acquired or seen confirmed their common misconception that there was only
>> one
>> programming language that was implemented everywhere. As a result, they
>> would not care about the implementations of ECMAScript, and their
>> differences. Instead they would begin or continue to ascribe
>> well-specified differences and the differences that must follow from
>> ECMAScript implementations being only the interface languages to APIs
>> like the DOM to "JavaScript bugs".
>
> "You would not"... "they would"... this is all conjecture.

Based on fact, unfortunately.

> I guess your point here is that using "JavaScript" as an umbrella term
> for ECMAScript implementations is harmful to newcomers.

Yes, it is.

> I will readily admit that "ECMAScript implementations" is more correct,

It is much more than that. The term is, unfortunately, widely unknown (we
have to thank the "javascript" for that, especially those writing books), so
it has the potential to stir interest in the truth of reality.

To those who want to know, it raises the question "What are ECMAScript
implementations?", as a consequence "What is ECMAScript?" and "Why is he
talking about ECMAScript implementations when we are discussing *the*
programming language, 'javascript'?".

As for the rest, I do not care about those who do not want to know, and
neither should you.

> but I dispute that any real harm is being done by using the name
> "JavaScript" loosely, or by accepting this usage from someone else. If a
> person is new to JS, chances are they've never heard of ECMAScript before.
> If they're serious about learning the language, they will find out about
> it soon enough; if they aren't serious, it doesn't matter either way.

But that is not what has happened in the past, it is not what is happening
right now (see the previous Subject of this thread) and it is not what is
going to happen in the future. To whom it is implied by a supposed expert
that they already know will not ask further questions to deepen and broaden
their knowledge. The evidence of that is all around you; you just have to
stop ignoring it.

> You smugly telling them that "There is no javascript", without any kind of
> explanation, will only confuse and alienate them.

This (non-)argument is really getting so old that it is beginning to acquire
a foul odor. As I have told you before, you will find it hard to find
occurrences in my postings where I stated that without pointing to the
ECMAScript Support Matrix. I concede that the first section of that
document might be misread as offensive and should be reworded; I am working
on it. But that does not change the fact that the evidence for the
statement can be found there, which is appreciated at least by some (from
whom I got rather positive feedback).

> And that's why I'm so annoyed by your constant intentionally cryptic
> replies in this group.

AISB, you really should pay more attention to what I am actually writing.

> If you really cared about educating people, you'd give them a polite
> pointer to a JS/ES terminology page.

If only you learned to understand what you read…

> Instead you'd rather annoy them (and many of the regulars) with one of you
> smartass replies.

See above.

>>> When there's a relevant distinction to be made between engines,
>>> dialects, or versions, we'll mention it.
>>
>> There are no dialects; that is just another form of the same fallacy.
>
> No, that's just you objecting to a word again.

Because it is the *wrong* word.

> Many others are fine with "dialects" in this context

Because they do not know or care about semantics. A *different* language is
_not_ a dialect of another language.

> (use Google to confirm this if you don't believe me).

Google search results have never been solid evidence that it is right to do
something. There are more follies in the world than stars in the sky.

> There's even a whole section on ECMAScript dialects on Wikipedia.

Wikipedia has never been good reference material with regard to this topic.
Indeed, all material about this topic in Wikipedia desperately needs a
number of revisions, or a rewrite.

> Whatever... call it "variants", if that makes you happy.

I will not. One different language is not a variant or dialect of another.
German is not a variant or dialect of English only because they both derive
from Germanic. In the same sense, Microsoft JScript (2.0+) et al. are not
variants or dialects of Netscape/Mozilla JavaScript (1.2+) only because they
are all implementations of ECMAScript. A cat is not a variant of a dog only
because they are both domesticated animals equipped with a tail, and so on.

>>> I'm certainly not going to write "conforming implementations of
>>> ECMAScript" every time.
>>
>> You do not have to. "ECMAScript implementations" usually suffices in a
>> general discussion.
>
> So does "JS", unless you're trying hard very to misunderstand somebody.

No, an unexplained use of "JS" carries with it the risk of being
misinterpreted as an abbreviation for JavaScript, with which we are coming
full circle.

>>> If you have a better suggestion, please let us hear it.
>>
>> Apparently you are thinking that by using the royal "we" you would be
>> more right or have more rights than if you had just used "I".
>
> Excuse me, but are you insane? "Royal we"? I was asking you to tell the
> group your suggestion. […]

You may be satisfied deluding yourself, but please do not insult my
intelligence.

>> No, we are _not_ discussing "javascript" here; we are discussing
>> ECMAScript implementations and applications thereof.
>
> I say that we do both. […]

There cannot be discussed both here. One is a misleading ambiguous misnomer
that should be abolished; the other is not.


PointedEars
--
realism: HTML 4.01 Strict
evangelism: XHTML 1.0 Strict
madness: XHTML 1.1 as application/xhtml+xml
-- Bjoern Hoehrmann

Thomas 'PointedEars' Lahn

unread,
Apr 29, 2012, 10:20:21 AM4/29/12
to
Thomas 'PointedEars' Lahn wrote:

> Stefan Weiss wrote:
>> I will readily admit that "ECMAScript implementations" is more correct,
>
> It is much more than that. The term is, unfortunately, widely unknown (we
> have to thank the "javascript" for that, especially those writing books),
^-- people

> so it has the potential to stir interest in the truth of reality.
> […]


PointedEars
--
Danny Goodman's books are out of date and teach practices that are
positively harmful for cross-browser scripting.
-- Richard Cornford, cljs, <cife6q$253$1$8300...@news.demon.co.uk> (2004)

John G Harris

unread,
Apr 29, 2012, 12:30:28 PM4/29/12
to
On Sat, 28 Apr 2012 at 22:23:38, in comp.lang.javascript, Thomas
'PointedEars' Lahn wrote:

<snip>
>Since JavaScript 1.0 and JScript 1.1 can be considered obsolete, the catch-
>all term for the rest of discussions is there: ECMAScript implementations.
<snip>

He finds two examples that destroy his proposed naming scheme so what
does he do? He deems them to be irrelevant : problem solved.

Unfortunately for him, they are still on-topic for this news group.

John
--
John Harris

Dr J R Stockton

unread,
Apr 29, 2012, 4:07:35 PM4/29/12
to
In comp.lang.javascript message <jnfabu$g0r$1...@news.albasani.net>, Sat,
28 Apr 2012 01:33:18, Stefan Weiss <krewe...@gmail.com> posted:

>
>There are other methods, too:
>
> parseInt(5/3)
Ooo nasty.
> ~~(5/3)
> (5/3) >> 0
> (5/3) | 0

Those only give integer division if the magnitude of the result is less
than 2^31 (2^31-0.5?). Math.floor(X/Y) will work for all possible
values of X & Y, but the result will be rounded to 53 significant bits.
Neither of those seems likely to affect the OP.

--
(c) John Stockton, nr London, UK. ?@merlyn.demon.co.uk Turnpike v6.05.
Website <http://www.merlyn.demon.co.uk/> - w. FAQish topics, links, acronyms
PAS EXE etc. : <http://www.merlyn.demon.co.uk/programs/> - see in 00index.htm
Dates - miscdate.htm estrdate.htm js-dates.htm pas-time.htm critdate.htm etc.

Evertjan.

unread,
Apr 30, 2012, 4:06:48 AM4/30/12
to
Dr J R Stockton wrote on 29 apr 2012 in comp.lang.javascript:

> In comp.lang.javascript message <jnfabu$g0r$1...@news.albasani.net>, Sat,
> 28 Apr 2012 01:33:18, Stefan Weiss <krewe...@gmail.com> posted:
>
>>
>>There are other methods, too:
>>
>> parseInt(5/3)
> Ooo nasty.
>> ~~(5/3)
>> (5/3) >> 0
>> (5/3) | 0
>
> Those only give integer division if the magnitude of the result is less
> than 2^31 (2^31-0.5?). Math.floor(X/Y) will work for all possible
> values of X & Y, but the result will be rounded to 53 significant bits.
> Neither of those seems likely to affect the OP.

The text "A maximum of 2^30 per customer" should be added to OP's page.

Tom

unread,
Apr 30, 2012, 4:33:19 AM4/30/12
to
On 4/30/2012 1:06 AM, Evertjan. wrote:
> Dr J R Stockton wrote on 29 apr 2012 in comp.lang.javascript:
>
>> In comp.lang.javascript message<jnfabu$g0r$1...@news.albasani.net>, Sat,
>> 28 Apr 2012 01:33:18, Stefan Weiss<krewe...@gmail.com> posted:
>>
>>>
>>> There are other methods, too:
>>>
>>> parseInt(5/3)
>> Ooo nasty.
>>> ~~(5/3)
>>> (5/3)>> 0
>>> (5/3) | 0
>>
>> Those only give integer division if the magnitude of the result is less
>> than 2^31 (2^31-0.5?). Math.floor(X/Y) will work for all possible
>> values of X& Y, but the result will be rounded to 53 significant bits.
>> Neither of those seems likely to affect the OP.
>
> The text "A maximum of 2^30 per customer" should be added to OP's page.
>

lol, the maximum is actually only 99. They'll be lucky if anyone orders
more than 1 though, it's a rather pricy item.

Scott Sauyet

unread,
Apr 30, 2012, 9:19:50 AM4/30/12
to
Stefan Weiss wrote:
> Thomas 'PointedEars' Lahn wrote:
>> Stefan Weiss wrote:
>>> On 2012-04-28 02:30, Michael Haufe (TNO) wrote:
>
>>>> function f(n){ return (n-(n%3))/3 }
>
>>> Ah yes, I forgot to add that one.
>
>> However, that approach requires three floating-point operations (and one
>> call of a user-defined function), whereas
>
>>   Math.floor(n / 3)
>
>> only requires two (and one property access and one built-in function call).
>> ISTM that therefore the cost and potential rounding error is greater with
>> the former than with the latter, and that the latter should be preferred,
>> at least for n >= 0.
>
> I also had the suspicion that rounding could introduce errors here, and
> I did a half-hearted search for such a case, but couldn't find one.

Does anyone have a case where this rounding is an issue? Although
these are floating point operations, since the first one to execute is
a modulus and the next is integeer subtraction, only the final
division seems likely to have real rounding issues, and that's done in
any of these solutions.

> Things might get interesting at the 2^32 boundary for bit operations,
> and 2^53 for arithmetic operations, but for calculations with numbers of
> that magnitude we need to take special precautions anyway.
>
> As for performance, function calls (built-in or user-defined) are
> generally much more expensive than numeric operations (unless the
> functions are inlined by the compiler). Without testing, I'd expect
> (a/b)|0 or (a/b)>>0 to perform best out of the expressions mentioned in
> this thread. Math.floor() would still be my choice for the "normal"
> case, small positive integers and few repetitions, because the intent of
> the code is immediately obvious.

I did a quick test on JSPerf:

<http://jsperf.com/floor-alternatives>

and the results are far from conclusive. I tested the three browsers
I have on my work desktop and my Android phone. In each case, the
threee bitwise versions clumped together:

~~(5 / 3)
(5 / 3) >> 0
(5 / 3) | 0

There was little to distinguish them, although the first might be a
bit less performant than the other two.

But there was a major discrepancy between `Math.floor(5 / 3)` and `(5
- (5 % 3)) / 3`. In Android 2.3.4, Math.floor was substantially
slower than the bitwise operators, which were substantially slower
than modulus-subtract-divide. In Chrome 19.0.1077, Math.floor was
slightly faster than the bitwise operators, and a bit slower than
modulus-subtract-dived. In Firefox 10, Math.floor was slightly slower
than most of the bitwise operators, but more than twice as fast as
modulus-subtract-divide. And in IE 8.0.3, Math.floor was quite a bit
slower than modulus-subtract-divide, which was slightly slower than
the bitwise operators. Of course the raw numbers for each browser was
significantly different.

So, I guess the answer is, as always, "it depends". And since even
the slowest off all these (Math.floor on IE) ran over 1.2 million
operations per second, it's likely to be a rare case where this speed
even matters.

-- Scott


Dr J R Stockton

unread,
May 1, 2012, 2:30:03 PM5/1/12
to
In comp.lang.javascript message <XnsA04566E1...@194.109.133.133>
, Mon, 30 Apr 2012 08:06:48, Evertjan. <exjxw.ha...@interxnl.net>
posted:

>Dr J R Stockton wrote on 29 apr 2012 in comp.lang.javascript:
>
>> In comp.lang.javascript message <jnfabu$g0r$1...@news.albasani.net>, Sat,
>> 28 Apr 2012 01:33:18, Stefan Weiss <krewe...@gmail.com> posted:
>>
>>>
>>>There are other methods, too:
>>>
>>> parseInt(5/3)
>> Ooo nasty.
>>> ~~(5/3)
>>> (5/3) >> 0
>>> (5/3) | 0
>>
>> Those only give integer division if the magnitude of the result is less
>> than 2^31 (2^31-0.5?). Math.floor(X/Y) will work for all possible
>> values of X & Y, but the result will be rounded to 53 significant bits.
>> Neither of those seems likely to affect the OP.
>
>The text "A maximum of 2^30 per customer" should be added to OP's page.

Discussion and advice in a thread commonly, as in this case, becomes
more general than is necessary for the purposes of the original
questioner. Therefore, it is appropriate to give general warnings.

--
(c) John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v6.05 MIME.
Web <http://www.merlyn.demon.co.uk/> - FAQish topics, acronyms, & links.
Proper <= 4-line sig. separator as above, a line exactly "-- " (SonOfRFC1036)
Do not Mail News to me. Before a reply, quote with ">" or "> " (SonOfRFC1036)

Dr J R Stockton

unread,
May 1, 2012, 2:48:53 PM5/1/12
to
In comp.lang.javascript message <67b160c3-9bd2-4872-9601-3125fff1c852@r1
3g2000vbg.googlegroups.com>, Mon, 30 Apr 2012 06:19:50, Scott Sauyet
<scott....@gmail.com> posted:

>
>But there was a major discrepancy between `Math.floor(5 / 3)` and `(5
>- (5 % 3)) / 3`. In Android 2.3.4, Math.floor was substantially
>slower than the bitwise operators, which were substantially slower
>than modulus-subtract-divide. In Chrome 19.0.1077, Math.floor was
>slightly faster than the bitwise operators, and a bit slower than
>modulus-subtract-dived. In Firefox 10, Math.floor was slightly slower
>than most of the bitwise operators, but more than twice as fast as
>modulus-subtract-divide. And in IE 8.0.3, Math.floor was quite a bit
>slower than modulus-subtract-divide, which was slightly slower than
>the bitwise operators. Of course the raw numbers for each browser was
>significantly different.

For simple cases like that, a browser might optimise out the formal call
to the actual function floor, in favour of working out the result at
compile time. Then, the speed tests would be misleading.

Such a browser might (or might not) be deluded by executing, say,
Math["flo"+"or"] = Math.random before the call-under-test. Certainly,
in MSIE 8, Firefox 12.0, Opera 11.62, Safari 5.1.5, Chrome 18.0,
Math.floor is not readonly :

X = Math.floor(3.77)
Math.floor = function () { return 2.96 }
Y = Math.floor(3.77)
Z = [X, Y] // gets [3,2.96]


--
(c) John Stockton, nr London, UK. ?@merlyn.demon.co.uk Turnpike 6.05 WinXP.
Web <http://www.merlyn.demon.co.uk/> - FAQ-type topics, acronyms, and links.
Command-prompt MiniTrue is useful for viewing/searching/altering files. Free,
DOS/Win/UNIX now 2.0.6; see <URL:http://www.merlyn.demon.co.uk/pc-links.htm>.

Gene Wirchenko

unread,
May 1, 2012, 10:30:09 PM5/1/12
to
On Tue, 1 May 2012 19:48:53 +0100, Dr J R Stockton
<repl...@merlyn.demon.co.uk.not.invalid> wrote:

[snip]

>For simple cases like that, a browser might optimise out the formal call
>to the actual function floor, in favour of working out the result at
>compile time. Then, the speed tests would be misleading.

There are lies, damned lies, statistics, damned statistics, and
then there are compiler benchmarks.

>Such a browser might (or might not) be deluded by executing, say,
>Math["flo"+"or"] = Math.random before the call-under-test. Certainly,
>in MSIE 8, Firefox 12.0, Opera 11.62, Safari 5.1.5, Chrome 18.0,
>Math.floor is not readonly :
>
> X = Math.floor(3.77)
> Math.floor = function () { return 2.96 }
> Y = Math.floor(3.77)
> Z = [X, Y] // gets [3,2.96]

I would be floored if I got a result like that.

Sincerely,

Gene Wirchenko
Message has been deleted

Gene Wirchenko

unread,
May 7, 2012, 5:36:06 PM5/7/12
to
On Mon, 07 May 2012 16:22:51 -0400, Puzzled
<scratch...@example.com> wrote:

[snip]

>One is rather tongue-in-cheek: if they have armies to back them
>up (i.e., are spoken by different political entities), they're
>languages. Thus, Danish, Norwegian, and Swedish are recognised
>as separate languages.

As I recall, a navy is also required. I do not know how this
applies to landlocked countries though there is:
http://en.wikipedia.org/wiki/Navies_of_landlocked_countries

[snip]

>Javascript and ECMAscript (what a dreadful example of
>bureaucratese!) are thus dialects much more than separate
>languages: neither has political independence, and they are
>largely mutually intelligible.

Armies of language supporters/fanboys/_____ attack each other on
the battlefield of the Net.

Sincerely,

Gene Wirchenko

Evertjan.

unread,
May 8, 2012, 4:40:59 AM5/8/12
to
Gene Wirchenko wrote on 07 mei 2012 in comp.lang.javascript:

> On Mon, 07 May 2012 16:22:51 -0400, Puzzled
> <scratch...@example.com> wrote:
>
> [snip]
>
>>One is rather tongue-in-cheek: if they have armies to back them
>>up (i.e., are spoken by different political entities), they're
>>languages. Thus, Danish, Norwegian, and Swedish are recognised
>>as separate languages.
>
> As I recall, a navy is also required.

Easy in Javascript, while you are in your element:

myElement.style.backgroundColor = 'navy';

or

myElement.style.backgroundColor = '#008';

<http://www.usingenglish.com/reference/idioms/in+your+element.html>

Gene Wirchenko

unread,
May 8, 2012, 12:29:10 PM5/8/12
to
On 08 May 2012 08:40:59 GMT, "Evertjan."
<exjxw.ha...@interxnl.net> wrote:

>Gene Wirchenko wrote on 07 mei 2012 in comp.lang.javascript:
>
>> On Mon, 07 May 2012 16:22:51 -0400, Puzzled
>> <scratch...@example.com> wrote:
>>
>> [snip]
>>
>>>One is rather tongue-in-cheek: if they have armies to back them
>>>up (i.e., are spoken by different political entities), they're
>>>languages. Thus, Danish, Norwegian, and Swedish are recognised
>>>as separate languages.
>>
>> As I recall, a navy is also required.
>
>Easy in Javascript, while you are in your element:
>
>myElement.style.backgroundColor = 'navy';
>
>or
>
>myElement.style.backgroundColor = '#008';
>
><http://www.usingenglish.com/reference/idioms/in+your+element.html>

Nicely played, sir!

Sincerely,

Gene Wirchenko
0 new messages