P: n/a

hey guys, im just writing a basic calculation at the moment, before
building on it for an ALevel piece of work. i can add/divide etc...
two numbers together yet i am having a major problem with the following
calculation:
z = x! / (x y)!
The following code is my attempt and i was hoping for a point in the
right direction as too where i am going wrong.. cheers
<html>
<head>
<FORM NAME = frmOne>
Number One: <INPUT TYPE = Text NAME = txtFirstNumber SIZE = 5 value
="">
Number Two: <INPUT TYPE = Text NAME = txtSecondNumber SIZE = 5 value
="">
<P>
Total: <INPUT TYPE = Text NAME = txtThirdNumber SIZE = 5 value = "">
<P>
<Input Type = Button NAME = b1 VALUE = "Calculate" onClick =
calculate()>
</FORM>
<script language = "javascript">
function calculate() {
A = document.frmOne.txtFirstNumber.value
B = document.frmOne.txtSecondNumber.value
C = (A ! / (A  B ) ! )
document.frmOne.txtThirdNumber.value = C
}
</script>
</head>
<body> Refresh to run the script again
</body>
Patrick  
Share this Question
P: n/a

Patrick,
There is no factorial operator in javascript. "A !" is not a valid java
expression. If you want to do factorials, you'll need to either write
the function yourself, or search for an example, of which I'm sure
there are thousands.
john  
P: n/a

ahhhh sorry about that.. where would i call the function seeing as i
already have the 'function calculate'? should i scrap all that and
start with the factorial function?
patrick  
P: n/a

On 09/12/2005 18:37, patrick_woflian wrote: [...] i am having a major problem with the following calculation:
z = x! / (x y)!
Whilst there is a unary ! operator in ECMAScript, it is not
arithmetical. It is, in fact, a logical NOT operator, as in many other
programming languages.
There is no builtin method for calculating factorials, so you will need
to write your own (which shouldn't be difficult).
[snip]
<head>
<FORM NAME = frmOne>
You may not place a FORM element within the HEAD element of a document.
The SCRIPT element may remain within HEAD, but the FORM must be moved to
the BODY element.
[snip]
<Input Type = Button NAME = b1 VALUE = "Calculate" onClick = calculate()>
That onclick attribute value must be quoted. Unless you know the rules
for what can, and what cannot be quoted, do the simple thing and quote
all attribute values.
[snip]
<script language = "javascript">
The language attribute has long been deprecated. Use the type attribute
instead:
<script type="text/javascript">
function calculate() { A = document.frmOne.txtFirstNumber.value B = document.frmOne.txtSecondNumber.value C = (A ! / (A  B ) ! )
These variables will become global, which is not good practice. Declare
them with the var keyword first.
There are other improvements that could be made, but they can wait for
now. One thing that I would recommend is that you markup documents
uniformly. Mixed case looks a bit of a mess. All lowercase (both for
elements and attributes) is generally easier to read.
Mike

Michael Winter
Prefix subject with [News] before replying by email.  
P: n/a

patrick_woflian wrote: hey guys, im just writing a basic calculation at the moment, before building on it for an ALevel piece of work. i can add/divide etc... two numbers together yet i am having a major problem with the following calculation:
z = x! / (x y)!
There is no builtin factorial function in javascript, you'll have to
write one yourself.
<script language = "javascript">
The language attribute is deprecate, use the type attribute instead:
<script type = "text/javascript">
function calculate() { A = document.frmOne.txtFirstNumber.value B = document.frmOne.txtSecondNumber.value C = (A ! / (A  B ) ! ) document.frmOne.txtThirdNumber.value = C }
It's my personal preference to explicitly declare variables, so as to
not to have potential collision with global variables.
var A, B, C;
And as for your factorial function, you can make the call here:
C = factorial(A) / factorial(A  B);
Here's a simple recursive factorial function you can use:
function factorial(n)
{
if(n == 1  n == 0) //your base case
return 1;
return n * factorial(n  1);
}
You can add additional checks, for example to see if n is a negative
value.  
P: n/a

patrick_woflian wrote: The following code is my attempt and i was hoping for a point in the right direction as too where i am going wrong.. cheers
<html>
<head>
<FORM NAME = frmOne>
That is not Valid HTML. <http://validator.w3.org/>
Number One: <INPUT TYPE = Text NAME = txtFirstNumber SIZE = 5 value ="">
Number Two: <INPUT TYPE = Text NAME = txtSecondNumber SIZE = 5 value =""> <P> Total: <INPUT TYPE = Text NAME = txtThirdNumber SIZE = 5 value = ""> <P>
Although all HTML specifications permit that, it is hardly legible and
potentially errorprone. Use spaces in tags only between element type
identifier and attributevaluepairs. Then there is no need for
uppercasing attribute names anymore.
`type="text"' is redundant because "text" is the initial value for the
`type' attribute of `input' elements, per DTD and browser behavior.
<Input Type = Button NAME = b1 VALUE = "Calculate" onClick = calculate()>
^^
Attribute values that contain either `(' or `)' must be enclosed
in straight single quotes (apostrophes) or double quotes.
</FORM>
<script language = "javascript">
The `language' attribute is deprecated in HTML 4.01, the `type' attribute
is required.
function calculate() { A = document.frmOne.txtFirstNumber.value
^
Variables that are defined without a preceding `var' keyword are global,
with potentially harmful sideeffects.
B = document.frmOne.txtSecondNumber.value
Although possible in DOM Level 0, Web standard W3C DOM Level 2 HTML calls
for accessing elements through their collections:
var B = document.forms['frmOne'].elements['txtSecondNumber'].value;
This referencing is downwards compatible to DOM Level 0 (IE3/NN3) if only
names (and not IDs) are used.
Passing a reference to the object representing the element that fired the
event makes it unnecessary to refer to the form by name/ID anymore:
<meta httpequiv="ContentScriptType" content="text/javascript">
...
<script type="text/javascript">
function fac(...)
{
...
return ...
}
function calc(o)
{
var f;
if (o && (f = o.form))
{
var es = f.elements;
if (es)
{
var
a = es['txtFirstNumber'].value,
b = es['txtSecondNumber'].value;
es['txtThirdNumber'].value = fac(a) / (a  b);
}
}
}
</script>
...
<form ...>
<input name="txtFirstNumber">
...
<input type="button" value="Calculcate" onclick="calc(this);">
</form>
C = (A ! / (A  B ) ! )
`!' is the Not Operator in ECMAScript implementations. It must be
_followed_ by the operand, not preceded by it.
There is no builtin equivalent for "faculty of x" (x!), you will have to
write a factorial function to achieve what you want, say you call fac(x)
instead. There are two approaches: iterative and recursive; the former
will allow you to calculate factorials of greater integers, of course still
with increasing loss of precision. Writing this function is left as an
exercise to the reader.
document.frmOne.txtThirdNumber.value = C
Although permitted without it due to automatic semicolon insertion,
statements should be followed by a semicolon in order to avoid
undesired sideeffects with that feature.
} [...]
Happy coding!
PointedEars  
P: n/a

Thomas 'PointedEars' Lahn wrote: function calc(o) { var f; if (o && (f = o.form)) { var es = f.elements; if (es) { var a = es['txtFirstNumber'].value, b = es['txtSecondNumber'].value;
es['txtThirdNumber'].value = fac(a) / (a  b);
Should be
es['txtThirdNumber'].value = fac(a) / fac(a  b);
of course.
And as for your Subject header:
Java is not JavaScript ("Java != JavaScript").
PointedEars  
P: n/a

If your factorial function was called "factorial", then you could
replace this line:
C = (A ! / (A  B ) ! )
with this line:
var C = (factorial(A) / (factorial(A  B));
The advice given to you by others regarding your HTML markup is
important.
john  
P: n/a

i have shortened my java script code to make it easier to understand...
this is my new code yet the factorial calculation still isn't working..
help!!
<html>
function factorial(n) {
if ((n == 0)  (n == 1))
return 1
else {
var result = (n * factorial(n1) );
return result
}
}
<script language = "javascript">
<!
var x = 0;
var y = 0;
var z = 0;
x = window.prompt("Enter first number..");
x = parseInt(x);
y = window.prompt("Enter second number..");
y = parseInt(y);
z = (factorial x / factorial (xy));
alert("THE ANSWER IS " + z);
//>
</script>
<body>
</body>
any comments would be great..  
P: n/a

patrick_woflian wrote: function factorial(n) { if ((n == 0)  (n == 1)) return 1 else { var result = (n * factorial(n1) ); return result
This can be shortened even further:
return n * factorial(n  1);
} }
Though it is not a requirement, it is good practice to end statements
with a semicolon.
<script language = "javascript"> <!
There is no need for SGML comments. The language attribute is
deprecated, use the type attribute instead:
z = (factorial x / factorial (xy));
You have a syntax error. Fix it to be like so:
z = factorial(x) / factorial(xy);
Another note, is your factorial function outside the script or within a
script? I can not tell from what you've posted. If it's outside, move
it inside the script tags.  
P: n/a

web.dev wrote on 09 dec 2005 in comp.lang.javascript : patrick_woflian wrote: function factorial(n) { if ((n == 0)  (n == 1)) return 1 else { var result = (n * factorial(n1) ); return result
This can be shortened even further:
return n * factorial(n  1);
This can be shortened even further,
[and will also catch negative inputs,
and give [not intended] results for nonintegers]
function factorial(n) {
return (n<2)?1:n*factorial(n);
}

Evertjan.
The Netherlands.
(Replace all crosses with dots in my emailaddress)  
P: n/a

JRS: In article <37****************@PointedEars.de>, dated Fri, 9 Dec
2005 20:16:31 local, seen in news:comp.lang.javascript, Thomas
'PointedEars' Lahn <Po*********@web.de> posted : There are two approaches: iterative and recursive; the former will allow you to calculate factorials of greater integers, of course still with increasing loss of precision.
Why do you say that? Both can calculate 170! but not 171!  giving the
same answer. Up to 18!, both will be exact; above that answers *may*
depend on whether the multiplications for N! start or finish with *N.
<URL:http://www.merlyn.demon.co.uk/jsindex.htm#BF> shows how to
determine factorials of numbers larger than 170.
Perhaps someone will check that one million factorial is about
8.263929417903883e5565708 ?

© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/jsindex.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.  
P: n/a

Evertjan. wrote: web.dev wrote on 09 dec 2005 in comp.lang.javascript:
patrick_woflian wrote:
function factorial(n) { if ((n == 0)  (n == 1)) return 1 else { var result = (n * factorial(n1) ); return result
This can be shortened even further:
return n * factorial(n  1);
This can be shortened even further, [and will also catch negative inputs, and give [not intended] results for nonintegers]
function factorial(n) { return (n<2)?1:n*factorial(n); }
A nonrecursive loop version is possibly faster, but the integer limit
of JavaScript is exceeded well before any meaningful result is
achieved even on a slow machine (170!), so I guess the issue is moot:
function factorial(n){
if (n > 0){
var x = 1;
do { x *= n; } while (n);
return x;
}
return (n==0)?1 : null; // [1]
}
1. What value should be returned for negative numbers? Probably null,
but maybe false or some error message? What should be done to
test/respond to noninteger values?

Rob  
P: n/a

RobG wrote on 10 dec 2005 in comp.lang.javascript : This can be shortened even further, [and will also catch negative inputs, and give [not intended] results for nonintegers]
function factorial(n) { return (n<2)?1:n*factorial(n); } A nonrecursive loop version is possibly faster, but the integer limit of JavaScript is exceeded well before any meaningful result is achieved even on a slow machine (170!), so I guess the issue is moot:
function factorial(n){ if (n > 0){ var x = 1; do { x *= n; } while (n); return x; } return (n==0)?1 : null; // [1] }
My point is not:
returning any value definitionwize if n<1, or not integer,
but:
preventing an endless loop with clientside timeout.
function factorial(n) {
return (n<2)?1:n*factorial(n);
}
does this fine.
it could be agued to prevent a too high n likewize:
function factorial(n) {
return (n<2n>170)?1:n*factorial(n);
} 1. What value should be returned for negative numbers? Probably null, but maybe false or some error message? What should be done to test/respond to noninteger values?
The same goes here, I am content with the result 1, since the real result
"undefined" in the mathemetical sense should be prevented on input.
The result 0 would give an error as divider in the OP's formula.
but if you wish we could output null
for "undefined [not integer or <1] or too large [>170] a factorial input"
..
function factorial(n) {
return (n<1n>170Math.floor(n)!=n)?null:
(n<2)?1:n*factorial(n);
}

Evertjan.
The Netherlands.
(Replace all crosses with dots in my emailaddress)  
P: n/a

On 20051209, Dr John Stockton <jr*@merlyn.demon.co.uk> wrote: JRS: In article <37****************@PointedEars.de>, dated Fri, 9 Dec 2005 20:16:31 local, seen in news:comp.lang.javascript, Thomas 'PointedEars' Lahn <Po*********@web.de> posted :
There are two approaches: iterative and recursive; the former will allow you to calculate factorials of greater integers, of course still with increasing loss of precision. Why do you say that? Both can calculate 170! but not 171!  giving the same answer. Up to 18!, both will be exact; above that answers *may* depend on whether the multiplications for N! start or finish with *N.
<URL:http://www.merlyn.demon.co.uk/jsindex.htm#BF> shows how to determine factorials of numbers larger than 170.
Perhaps someone will check that one million factorial is about 8.263929417903883e5565708 ?
**** SENDING othernet.fidonet.nz.games *****
Group othernet.fidonet.nz.games 11,11,11
state: 1011
othernet.fidonet.nz.games 11 of 11 (from 127.0.0.1)
ff=0
downloaded othernet.fidonet.nz.games 11,11,11
**** RECIEVING othernet.fidonet.nz.genealogy *****
Group othernet.fidonet.nz.genealogy 2,2,2
state: 22
othernet.fidonet.nz.genealogy 2 of 2 (from news.free.net.nz)
ff=0
downloaded othernet.fidonet.nz.genealogy 2,2,2
**** SENDING othernet.fidonet.nz.genealogy *****
Group othernet.fidonet.nz.genealogy 11,11,11
state: 1011
othernet.fidonet.nz.genealogy 11 of 11 (from 127.0.0.1)
ff=0
downloaded othernet.fidonet.nz.genealogy 11,11,11
**** RECIEVING othernet.fidonet.nz.general *****
Group othernet.fidonet.nz.general 2,2,2
state: 22
othernet.fidonet.nz.general 2 of 2 (from news.free.net.nz)
ff=0
downloaded othernet.fidonet.nz.general 2,2,2
**** SENDING othernet.fidonet.nz.general *****
Group othernet.fidonet.nz.general 11,11,11
state: 1011
othernet.fidonet.nz.general 11 of 11 (from 127.0.0.1)
ff=0
downloaded othernet.fidonet.nz.general 11,11,11
**** RECIEVING othernet.fidonet.nz.lang.c *****
Group othernet.fidonet.nz.lang.c 2,2,2
state: 22
othernet.fidonet.nz.lang.c 2 of 2 (from news.free.net.nz)
ff=0
downloaded othernet.fidonet.nz.lang.c 2,2,2
**** SENDING othernet.fidonet.nz.lang.c *****
Group othernet.fidonet.nz.lang.c 11,11,11
state: 1011
othernet.fidonet.nz.lang.c 11 of 11 (from 127.0.0.1)
ff=0
downloaded othernet.fidonet.nz.lang.c 11,11,11
**** RECIEVING othernet.fidonet.nz.music *****
Group othernet.fidonet.nz.music 2,2,2
state: 22
othernet.fidonet.nz.music 2 of 2 (from news.free.net.nz)
ff=0
downloaded othernet.fidonet.nz.music 2,2,2
**** SENDING othernet.fidonet.nz.music *****
Group othernet.fidonet.nz.music 11,11,11
state: 1011
othernet.fidonet.nz.music 11 of 11 (from 127.0.0.1)
ff=0
downloaded othernet.fidonet.nz.music 11,11,11
**** RECIEVING othernet.fidonet.nz.rpg.chat *****
Group othernet.fidonet.nz.rpg.chat 2,2,2
state: 22
othernet.fidonet.nz.rpg.chat 2 of 2 (from news.free.net.nz)
ff=0
downloaded othernet.fidonet.nz.rpg.chat 2,2,2
**** SENDING othernet.fidonet.nz.rpg.chat *****
Group othernet.fidonet.nz.rpg.chat 11,11,11
state: 1011
othernet.fidonet.nz.rpg.chat 11 of 11 (from 127.0.0.1)
ff=0
downloaded othernet.fidonet.nz.rpg.chat 11,11,11
**** RECIEVING othernet.fidonet.nz.rpg.misc *****
Group othernet.fidonet.nz.rpg.misc 2,2,2
state: 22
othernet.fidonet.nz.rpg.misc 2 of 2 (from news.free.net.nz)
ff=0
downloaded othernet.fidonet.nz.rpg.misc 2,2,2
**** SENDING othernet.fidonet.nz.rpg.misc *****
Group othernet.fidonet.nz.rpg.misc 11,11,11
state: 1011
othernet.fidonet.nz.rpg.misc 11 of 11 (from 127.0.0.1)
ff=0
downloaded othernet.fidonet.nz.rpg.misc 11,11,11
**** RECIEVING othernet.fidonet.nz.scifi *****
Group othernet.fidonet.nz.scifi 2,2,2
state: 22
othernet.fidonet.nz.scifi 2 of 2 (from news.free.net.nz)
ff=0
downloaded othernet.fidonet.nz.scifi 2,2,2
**** SENDING othernet.fidonet.nz.scifi *****
Group othernet.fidonet.nz.scifi 11,11,11
state: 1011
othernet.fidonet.nz.scifi 11 of 11 (from 127.0.0.1)
ff=0
downloaded othernet.fidonet.nz.scifi 11,11,11
**** RECIEVING alt.binaries.schematics.electronic *****
Group alt.binaries.schematics.electronic 1817,1817,1817
state: 4371830
alt.binaries.schematics.electronic 1817 of 1830 (from news.free.net.nz)
transfer_article: <8v********************************@4ax.com>
***NEW, TOO  NEW!!!**
F10 key ==> File Edit Search Buffers Windows System Help
Newsgroups: comp.lang.javascript
From: Jasen Betts <ja***@free.net.nospam.nz>
Subject: Re: factorial numbers in java script
References: <11*********************@o13g2000cwo.googlegroups. com>
<3706499.lr0$
Organization:
FollowupTo:
On 20051209, Dr John Stockton <jr*@merlyn.demon.co.uk> wrote: JRS: In article <37****************@PointedEars.de>, dated Fri, 9 Dec 2005 20:16:31 local, seen in news:comp.lang.javascript, Thomas 'PointedEars' Lahn <Po*********@web.de> posted :
There are two approaches: iterative and recursive; the former will allow you to calculate factorials of greater integers, of course still with increasing loss of precision. Why do you say that? Both can calculate 170! but not 171!  giving the same answer. Up to 18!, both will be exact; above that answers *may* depend on whether the multiplications for N! start or finish with *N.
<URL:http://www.merlyn.demon.co.uk/jsindex.htm#BF> shows how to determine factorials of numbers larger than 170.
Perhaps someone will check that one million factorial is about 8.263929417903883e5565708 ?
**** SENDING othernet.fidonet.nz.games *****
Group othernet.fidonet.nz.games 11,11,11
state: 1011
othernet.fidonet.nz.games 11 of 11 (from 127.0.0.1)
ff=0
downloaded othernet.fidonet.nz.games 11,11,11
**** RECIEVING othernet.fidonet.nz.genealogy *****
Group othernet.fidonet.nz.genealogy 2,2,2
state: 22
othernet.fidonet.nz.genealogy 2 of 2 (from news.free.net.nz)
ff=0
downloaded othernet.fidonet.nz.genealogy 2,2,2
**** SENDING othernet.fidonet.nz.genealogy *****
Group othernet.fidonet.nz.genealogy 11,11,11
state: 1011
othernet.fidonet.nz.genealogy 11 of 11 (from 127.0.0.1)
ff=0
downloaded othernet.fidonet.nz.genealogy 11,11,11
**** RECIEVING othernet.fidonet.nz.general *****
Group othernet.fidonet.nz.general 2,2,2
state: 22
othernet.fidonet.nz.general 2 of 2 (from news.free.net.nz)
ff=0
downloaded othernet.fidonet.nz.general 2,2,2
**** SENDING othernet.fidonet.nz.general *****
Group othernet.fidonet.nz.general 11,11,11
state: 1011
othernet.fidonet.nz.general 11 of 11 (from 127.0.0.1)
ff=0
downloaded othernet.fidonet.nz.general 11,11,11
**** RECIEVING othernet.fidonet.nz.lang.c *****
Group othernet.fidonet.nz.lang.c 2,2,2
state: 22
othernet.fidonet.nz.lang.c 2 of 2 (from news.free.net.nz)
ff=0
downloaded othernet.fidonet.nz.lang.c 2,2,2
**** SENDING othernet.fidonet.nz.lang.c *****
Group othernet.fidonet.nz.lang.c 11,11,11
state: 1011
othernet.fidonet.nz.lang.c 11 of 11 (from 127.0.0.1)
ff=0
downloaded othernet.fidonet.nz.lang.c 11,11,11
**** RECIEVING othernet.fidonet.nz.music *****
Group othernet.fidonet.nz.music 2,2,2
state: 22
othernet.fidonet.nz.music 2 of 2 (from news.free.net.nz)
ff=0
downloaded othernet.fidonet.nz.music 2,2,2
**** SENDING othernet.fidonet.nz.music *****
Group othernet.fidonet.nz.music 11,11,11
state: 1011
othernet.fidonet.nz.music 11 of 11 (from 127.0.0.1)
ff=0
downloaded othernet.fidonet.nz.music 11,11,11
**** RECIEVING othernet.fidonet.nz.rpg.chat *****
Group othernet.fidonet.nz.rpg.chat 2,2,2
state: 22
othernet.fidonet.nz.rpg.chat 2 of 2 (from news.free.net.nz)
ff=0
downloaded othernet.fidonet.nz.rpg.chat 2,2,2
**** SENDING othernet.fidonet.nz.rpg.chat *****
Group othernet.fidonet.nz.rpg.chat 11,11,11
state: 1011
othernet.fidonet.nz.rpg.chat 11 of 11 (from 127.0.0.1)
ff=0
downloaded othernet.fidonet.nz.rpg.chat 11,11,11
**** RECIEVING othernet.fidonet.nz.rpg.misc *****
Group othernet.fidonet.nz.rpg.misc 2,2,2
state: 22
othernet.fidonet.nz.rpg.misc 2 of 2 (from news.free.net.nz)
ff=0
downloaded othernet.fidonet.nz.rpg.misc 2,2,2
**** SENDING othernet.fidonet.nz.rpg.misc *****
Group othernet.fidonet.nz.rpg.misc 11,11,11
state: 1011
othernet.fidonet.nz.rpg.misc 11 of 11 (from 127.0.0.1)
ff=0
downloaded othernet.fidonet.nz.rpg.misc 11,11,11
**** RECIEVING othernet.fidonet.nz.scifi *****
Group othernet.fidonet.nz.scifi 2,2,2
state: 22
othernet.fidonet.nz.scifi 2 of 2 (from news.free.net.nz)
ff=0
downloaded othernet.fidonet.nz.scifi 2,2,2
**** SENDING othernet.fidonet.nz.scifi *****
Group othernet.fidonet.nz.scifi 11,11,11
state: 1011
othernet.fidonet.nz.scifi 11 of 11 (from 127.0.0.1)
ff=0
downloaded othernet.fidonet.nz.scifi 11,11,11
**** RECIEVING alt.binaries.schematics.electronic *****
Group alt.binaries.schematics.electronic 1817,1817,1817
state: 4371830
alt.binaries.schematics.electronic 1817 of 1830 (from news.free.net.nz)
transfer_article: <8v********************************@4ax.com>
***NEW, TOO  NEW!!!**
F10 key ==> File Edit Search Buffers Windows System Help
Newsgroups: comp.lang.javascript
From: Jasen Betts <ja***@free.net.nospam.nz>
Subject: Re: factorial numbers in java script
References: <11*********************@o13g2000cwo.googlegroups. com>
<3706499.lr0$
Organization:
FollowupTo:
On 20051209, Dr John Stockton <jr*@merlyn.demon.co.uk> wrote: JRS: In article <37****************@PointedEars.de>, dated Fri, 9 Dec 2005 20:16:31 local, seen in news:comp.lang.javascript, Thomas 'PointedEars' Lahn <Po*********@web.de> posted :
There are two approaches: iterative and recursive; the former will allow you to calculate factorials of greater integers, of course still with increasing loss of precision. Why do you say that? Both can calculate 170! but not 171!  giving the same answer. Up to 18!, both will be exact; above that answers *may* depend on whether the multiplications for N! start or finish with *N.
<URL:http://www.merlyn.demon.co.uk/jsindex.htm#BF> shows how to determine factorials of numbers larger than 170.
Perhaps someone will check that one million factorial is about 8.263929417903883e5565708 ?
**** SENDING othernet.fidonet.nz.games *****
Group othernet.fidonet.nz.games 11,11,11
state: 1011
othernet.fidonet.nz.games 11 of 11 (from 127.0.0.1)
ff=0
downloaded othernet.fidonet.nz.games 11,11,11
**** RECIEVING othernet.fidonet.nz.genealogy *****
Group othernet.fidonet.nz.genealogy 2,2,2
state: 22
othernet.fidonet.nz.genealogy 2 of 2 (from news.free.net.nz)
ff=0
downloaded othernet.fidonet.nz.genealogy 2,2,2
**** SENDING othernet.fidonet.nz.genealogy *****
Group othernet.fidonet.nz.genealogy 11,11,11
state: 1011
othernet.fidonet.nz.genealogy 11 of 11 (from 127.0.0.1)
ff=0
downloaded othernet.fidonet.nz.genealogy 11,11,11
**** RECIEVING othernet.fidonet.nz.general *****
Group othernet.fidonet.nz.general 2,2,2
state: 22
othernet.fidonet.nz.general 2 of 2 (from news.free.net.nz)
ff=0
downloaded othernet.fidonet.nz.general 2,2,2
**** SENDING othernet.fidonet.nz.general *****
Group othernet.fidonet.nz.general 11,11,11
state: 1011
othernet.fidonet.nz.general 11 of 11 (from 127.0.0.1)
ff=0
downloaded othernet.fidonet.nz.general 11,11,11
**** RECIEVING othernet.fidonet.nz.lang.c *****
Group othernet.fidonet.nz.lang.c 2,2,2
state: 22
othernet.fidonet.nz.lang.c 2 of 2 (from news.free.net.nz)
ff=0
downloaded othernet.fidonet.nz.lang.c 2,2,2
**** SENDING othernet.fidonet.nz.lang.c *****
Group othernet.fidonet.nz.lang.c 11,11,11
state: 1011
othernet.fidonet.nz.lang.c 11 of 11 (from 127.0.0.1)
ff=0
downloaded othernet.fidonet.nz.lang.c 11,11,11
**** RECIEVING othernet.fidonet.nz.music *****
Group othernet.fidonet.nz.music 2,2,2
state: 22
othernet.fidonet.nz.music 2 of 2 (from news.free.net.nz)
ff=0
downloaded othernet.fidonet.nz.music 2,2,2
**** SENDING othernet.fidonet.nz.music *****
Group othernet.fidonet.nz.music 11,11,11
state: 1011
othernet.fidonet.nz.music 11 of 11 (from 127.0.0.1)
ff=0
downloaded othernet.fidonet.nz.music 11,11,11
**** RECIEVING othernet.fidonet.nz.rpg.chat *****
Group othernet.fidonet.nz.rpg.chat 2,2,2
state: 22
othernet.fidonet.nz.rpg.chat 2 of 2 (from news.free.net.nz)
ff=0
downloaded othernet.fidonet.nz.rpg.chat 2,2,2
**** SENDING othernet.fidonet.nz.rpg.chat *****
Group othernet.fidonet.nz.rpg.chat 11,11,11
state: 1011
othernet.fidonet.nz.rpg.chat 11 of 11 (from 127.0.0.1)
ff=0
downloaded othernet.fidonet.nz.rpg.chat 11,11,11
**** RECIEVING othernet.fidonet.nz.rpg.misc *****
Group othernet.fidonet.nz.rpg.misc 2,2,2
state: 22
othernet.fidonet.nz.rpg.misc 2 of 2 (from news.free.net.nz)
ff=0
downloaded othernet.fidonet.nz.rpg.misc 2,2,2
**** SENDING othernet.fidonet.nz.rpg.misc *****
Group othernet.fidonet.nz.rpg.misc 11,11,11
state: 1011
othernet.fidonet.nz.rpg.misc 11 of 11 (from 127.0.0.1)
ff=0
downloaded othernet.fidonet.nz.rpg.misc 11,11,11
**** RECIEVING othernet.fidonet.nz.scifi *****
Group othernet.fidonet.nz.scifi 2,2,2
state: 22
othernet.fidonet.nz.scifi 2 of 2 (from news.free.net.nz)
ff=0
downloaded othernet.fidonet.nz.scifi 2,2,2
**** SENDING othernet.fidonet.nz.scifi *****
Group othernet.fidonet.nz.scifi 11,11,11
state: 1011
othernet.fidonet.nz.scifi 11 of 11 (from 127.0.0.1)
ff=0
downloaded othernet.fidonet.nz.scifi 11,11,11
**** RECIEVING alt.binaries.schematics.electronic *****
Group alt.binaries.schematics.electronic 1817,1817,1817
state: 4371830
alt.binaries.schematics.electronic 1817 of 1830 (from news.free.net.nz)
transfer_article: <8v********************************@4ax.com>
***NEW, TOO  NEW!!!**
F10 key ==> File Edit Search Buffers Windows System Help
Newsgroups: comp.lang.javascript
From: Jasen Betts <ja***@free.net.nospam.nz>
Subject: Re: factorial numbers in java script
References: <11*********************@o13g2000cwo.googlegroups. com>
<3706499.lr0$
Organization:
FollowupTo:
On 20051209, Dr John Stockton <jr*@merlyn.demon.co.uk> wrote: JRS: In article <37****************@PointedEars.de>, dated Fri, 9 Dec 2005 20:16:31 local, seen in news:comp.lang.javascript, Thomas 'PointedEars' Lahn <Po*********@web.de> posted :
There are two approaches: iterative and recursive; the former will allow you to calculate factorials of greater integers, of course still with increasing loss of precision.
Why do you say that? Both can calculate 170! but not 171!  giving the same answer. Up to 18!, both will be exact; above that answers *may* depend on whether the multiplications for N! start or finish with *N.
<URL:http://www.merlyn.demon.co.uk/jsindex.htm#BF> shows how to determine factorials of numbers larger than 170.
Perhaps someone will check that one million factorial is about 8.263929417903883e5565708 ?
8.263931688330718e5565708
was the approximation I got using this script.
<!DOCTYPE HTML PUBLIC "//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<script language="javascript">
function fak(m)
{
var a=1,n=+m,r=0;
do{
a*=n;
if( a>1e16){ a=a/1e16; r=r+16;}
}
while (n>0 )
if( a>100000000){ a=a/100000000 ; r=r+8;}
if( a>10000){ a=a/10000 ; r=r+4;}
if( a>100){ a=a/100 ; r=r+2;}
if( a>10){ a=a/10 ; r=r+1;}
document.MyForm.result.value=a+'e'+r;
return true;
}
</script>
</head>
<body>
<form name="MyForm">
<input onchange="fak(this.value)">!=
<input style="width:30em" name="result" readonly="readonly">
</form>
</body>
</html>

Bye.
Jasen  
P: n/a

Dr John Stockton wrote: [...] Thomas 'PointedEars' Lahn [...] posted : There are two approaches: iterative and recursive; the former will allow you to calculate factorials of greater integers, of course still with increasing loss of precision.
Why do you say that? [...]
Because how many recursive calls are possible, thus which is the greatest
factorial that can be calculated through that approach, is limited by the
range for IEEE doubles and the stack size; the greatest factorial that can
be calculated through the iterative approach is only limited by the range
for IEEE doubles.
PointedEars  
P: n/a

In article
<43***********************@perqv1newsreader01.iinet.net.au>, RobG
<rg***@iinet.net.auau> writes
<snip> 1. What value should be returned for negative numbers? Probably null, but maybe false or some error message? What should be done to test/respond to noninteger values?
Recall that x! is defined for all real numbers, except that for 1, 2,
3, ... it goes off to +/ infinity (and drops down to nearly zero in
between). I suspect this is more than you really wanted to know :)
What should be done for negative and nonintegral values depends on the
customer's requirements.
alert("I don't do that");
is the simplest answer.
John

John Harris  
P: n/a

In article <TI**************@merlyn.demon.co.uk>, Dr John Stockton
<jr*@merlyn.demon.co.uk> writes
<snip> Perhaps someone will check that one million factorial is about 8.263929417903883e5565708 ?
8.263931686266318e5565708
is the value I get using Stirling's formula. It is probably accurate to
10 digits or so if IE's Math object is reasonably good.
The accuracy of x! depends on x being 'large'. For comparison, I get
1! = 1.0017262166905087 e 0
4! = 2.4000001753028925 e 1
10! = 3.628800000432076 e 6
John
<SCRIPT type="text/javascript">
function LnFact(x)
// Stirling's approximation
// LnFact(x) = ln(x!)
{
return Math.log(2*Math.PI)/2 +
(x + 0.5)*Math.log(x)  x +
1/12/x  1/360/x/x/x + 1/1260/x/x/x/x/x +
1/1680/x/x/x/x/x/x/x + 1/1188/x/x/x/x/x/x/x/x/x;
}
function DispFact(x)
// Display x!
{
var lf10 = LnFact(x)*Math.LOG10E;
var fexp = Math.floor(lf10); // exponent
var fmant = Math.pow(10, lf10  fexp); // mantissa
document.writeln
(x, "<strong>!</strong> = ",
fmant, " e ", fexp, "<br>");
}
DispFact(1);
DispFact(4);
DispFact(10);
DispFact(1e6);
</SCRIPT>

John Harris  
P: n/a

John G Harris wrote: In article <43***********************@perqv1newsreader01.iinet.net.au>, RobG <rg***@iinet.net.auau> writes
<snip>
1. What value should be returned for negative numbers? Probably null, but maybe false or some error message? What should be done to test/respond to noninteger values?
Recall that x! is defined for all real numbers, except that for 1, 2, 3, ... it goes off to +/ infinity (and drops down to nearly zero in between).
No, I don't  factorials are only defined for positive integers and
zero, where 0! = 1.
I suspect this is more than you really wanted to know :)
Yes (see above).
What should be done for negative and nonintegral values depends on the customer's requirements.
Exactly, and you didn't state what that was. My intention was to raise
the issue so that you thought about it, I didn't want to guess at a
solution that may not be appropriate (for you or your client).
alert("I don't do that"); is the simplest answer.
But not very elegant. Your code should ensure negative numbers are
never passed to the factorial function by checking the data input, not
by barfing at some later stage that may be several steps away from where
the actual error occurred.

Rob  
P: n/a

In article
<43**********************@perqv1newsreader01.iinet.net.au>, RobG
<rg***@iinet.net.au> writes John G Harris wrote: In article <43***********************@perqv1newsreader01.iinet.net.au>, RobG <rg***@iinet.net.auau> writes <snip>
1. What value should be returned for negative numbers? Probably null, but maybe false or some error message? What should be done to test/respond to noninteger values? Recall that x! is defined for all real numbers, except that for 1, 2, 3, ... it goes off to +/ infinity (and drops down to nearly zero in between).
No, I don't  factorials are only defined for positive integers and zero, where 0! = 1.
That's the schoolbook definition. In a serious textbook x! is defined
as an integral, for any real x. The book then goes on to prove that
(x+1)! = (x+1)*x and that 0! = 1. From this you can use a for loop to
calculate 1!, 2!, 3!, ..., just as in a school textbook. I suspect this is more than you really wanted to know :)
Yes (see above).
What should be done for negative and nonintegral values depends on the customer's requirements.
Exactly, and you didn't state what that was. My intention was to raise the issue so that you thought about it, I didn't want to guess at a solution that may not be appropriate (for you or your client).
I'm not the original poster so I don't know what's needed. My intention
was to point out that the answer depends on the context.
For instance, if the context is statistical tests of significance then
0.5! is likely to crop up. On the other hand, if the context is
combinations then both 0.5 and 0 are very likely to be errors. alert("I don't do that"); is the simplest answer.
But not very elegant. Your code should ensure negative numbers are never passed to the factorial function by checking the data input, not by barfing at some later stage that may be several steps away from where the actual error occurred.
Obviously, silly values should be trapped as close to the input as
possible. Then you have to choose what the factorial function should do.
One choice is to ignore the problem as it's not going to happen. The
other is to check the parameter and return a special value if it's bad.
This has the disadvantage that you have to check the function with
several silly values, not just sensible ones.
John

John Harris  
P: n/a

JRS: In article <439a1e2c$0$22292$5a62ac22@perqv1newsreader
01.iinet.net.au>, dated Sat, 10 Dec 2005 10:15:40 local, seen in
news:comp.lang.javascript, RobG <rg***@iinet.net.auau> posted : function factorial(n) { return (n<2)?1:n*factorial(n); } A nonrecursive loop version is possibly faster, but the integer limit of JavaScript is exceeded well before any meaningful result is achieved even on a slow machine (170!), so I guess the issue is moot:
1. What value should be returned for negative numbers? Probably null, but maybe false or some error message? What should be done to test/respond to noninteger values?
For arguments where the true or apparent result exceeds the numeric
capacity of an IEEE Double, it seems reasonable to return an Infinity.
Returning anything that can be coerced into a finite number seems unwise
as it may lead to undetected error; but returning something that coerces
to 0 may be safe enough. Returning NaN seems appropriate.
There is a function known to mathematicians that basically matches
factorial for the positive, or nonnegative, or greater than 1,
integers, but is actually defined over (at least) the (positive?) reals;
ISTR it's the Gamma function, but ICBW.

© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/jsindex.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.  
P: n/a

JRS: In article <Xn********************@194.109.133.242>, dated Sat, 10
Dec 2005 09:02:54 local, seen in news:comp.lang.javascript, Evertjan.
<ex**************@interxnl.net> posted : it could be agued to prevent a too high n likewize:
function factorial(n) { return (n<2n>170)?1:n*factorial(n); }
(a) ISTM that 1 should NOT be the result for an outofrange argument.
(b) ISTM that the tests should be inverted, so that a NaN argument
counts as outofrange; or that there should be a specific isNaN test.
(c) ISTM that, ideally, the 170 test should be done only once, since it
can only fail on the first attempt.
(d) Probably, for most or all practical applications of factorial, an
argument less than zero should give NaN, as should a noninteger
argument.
function Fac(m) { return m<2 ? 1 : m*Fac(m) }
function Factorial(n) {
if (isNaN(n)) return NaN
if (n<0) return NaN
if (n>170) return Infinity
if (n%1) return NaN
return Fac(n) }
or
function Factorial(n) {
if (isNaN(n)  n<0  n%1) return NaN
if (n>170) return Infinity
return Fac(n) }
Then one can use Factorial in test code, and Fac in debugged code!

© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/jsindex.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.  
P: n/a

JRS: In article <31****************@PointedEars.de>, dated Sat, 10 Dec
2005 12:55:36 local, seen in news:comp.lang.javascript, Thomas
'PointedEars' Lahn <Po*********@web.de> posted : Dr John Stockton wrote:
[...] Thomas 'PointedEars' Lahn [...] posted : There are two approaches: iterative and recursive; the former will allow you to calculate factorials of greater integers, of course still with increasing loss of precision.
Why do you say that? [...]
Because how many recursive calls are possible, thus which is the greatest factorial that can be calculated through that approach, is limited by the range for IEEE doubles and the stack size; the greatest factorial that can be calculated through the iterative approach is only limited by the range for IEEE doubles.
You meant "... might allow your readers ...".
function Fac(m) { return m<2 ? 1 : m*Fac(m) }
My small system will currently calculate (as Infinity) Fac(357) but not
Fac(358).

© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/jsindex.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.  
P: n/a

JRS: In article <1a*****************@clunker.homenet>, dated Sat, 10
Dec 2005 10:30:30 local, seen in news:comp.lang.javascript, Jasen Betts
<ja***@free.net.nospam.nz> posted : On 20051209, Dr John Stockton <jr*@merlyn.demon.co.uk> wrote:
<URL:http://www.merlyn.demon.co.uk/jsindex.htm#BF> shows how to determine factorials of numbers larger than 170.
Perhaps someone will check that one million factorial is about 8.263929417903883e5565708 ?
**** SENDING othernet.fidonet.nz.games ***** ...
??? 8.263931688330718e5565708
was the approximation I got using this script. ...
That and the other answer are both quite different methods, and ISTM
that they agree as well as can be expected since two of them have a
million rounding errors and the third is nominally approximate.
Thanks to both.

© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 MIME. ©
Web <URL:http://www.merlyn.demon.co.uk/>  FAQqish topics, acronyms & links;
Astro stuff via astron1.htm, gravity0.htm ; quotings.htm, pascal.htm, etc.
No Encoding. Quotes before replies. Snip well. Write clearly. Don't Mail News.  
P: n/a

Dr John Stockton wrote: [...] Thomas 'PointedEars' Lahn [...] posted : Dr John Stockton wrote: [...] Thomas 'PointedEars' Lahn [...] posted : There are two approaches: iterative and recursive; the former will allow you to calculate factorials of greater integers, of course still with increasing loss of precision. Why do you say that? [...]Because how many recursive calls are possible, thus which is the greatest factorial that can be calculated through that approach, is limited by the range for IEEE doubles and the stack size; the greatest factorial that can be calculated through the iterative approach is only limited by the range for IEEE doubles.
You meant "... might allow your readers ...".
Pardon?
function Fac(m) { return m<2 ? 1 : m*Fac(m) }
Negative arguments should not return 1, and I would not want to rely on
automatic semicolon insertion here.
My small system will currently calculate (as Infinity) Fac(357) but not Fac(358).
That's nice for you.
PointedEars  
P: n/a

John G Harris wrote: In article <43**********************@perqv1newsreader01.iinet.net.au>, RobG <rg***@iinet.net.au> writes
John G Harris wrote:
In article <43***********************@perqv1newsreader01.iinet.net.au>, RobG <rg***@iinet.net.auau> writes <snip>
1. What value should be returned for negative numbers? Probably null, but maybe false or some error message? What should be done to test/respond to noninteger values?
Recall that x! is defined for all real numbers, except that for 1, 2, 3, ... it goes off to +/ infinity (and drops down to nearly zero in between). No, I don't  factorials are only defined for positive integers and zero, where 0! = 1.
That's the schoolbook definition. In a serious textbook x! is defined as an integral, for any real x. The book then goes on to prove that (x+1)! = (x+1)*x and that 0! = 1. From this you can use a for loop to calculate 1!, 2!, 3!, ..., just as in a school textbook.
The 'schoolbook' definition is the formal definition of the factorial
for natural numbers (including zero) which I think can be assumed unless
something more complex is indicated.
The basic factorial function can be modified to estimate factorials for
fractions, but I don't think that alters the above. I'd bee keen to see
a JavaScript implementation of the factorial function for nonintegers. ;)
The modified function can be used to determine values for negative
fractions but their behaviour is bizarre and as far as I can tell have
no useful purpose  exactly what is complex negative infinity?
Every formal definition of a factorial I can find only relates to
numbers greater than or equal to zero, so I'll continue to believe that
n! is undefined where n<0.
The Wolfram Research page probably has more than any of us wishes to know:
<URL: http://mathworld.wolfram.com/Factorial.html >
[...] I'm not the original poster so I don't know what's needed. My intention was to point out that the answer depends on the context.
Ooops, sorry. I got my threads crossed. :x For instance, if the context is statistical tests of significance then 0.5! is likely to crop up. On the other hand, if the context is combinations then both 0.5 and 0 are very likely to be errors.
In that case I'd try to avoid nonintegers, which should be possible in
most cases.
Simplified functions can be defined for specific noninteger cases  a
function that calculates halfinteger factorials is below (the error
message could be more useful :) ):
function halfFactorial(n)
{
if ( n < 0  (n0.5) % 1) {
return 'Only +ve halfintegers will do, e.g. 0.5, 3.5, etc.';
}
var rtPI = Math.sqrt(Math.atan(1)*4);
var x=1;
while (n>0){
x *= n;
}
return (rtPI*x).toFixed(2);
}
Which gives:
0.5! = 0.89
1.5! = 1.33
2.5! = 3.32
3.5! = 11.63
4.5! = 52.34
But it should only be used for halves, not whole numbers and I have no
idea what it would be useful for. A general solution for noninteger
factorials written in JavaScript might be useful. :)
[...]
Obviously, silly values should be trapped as close to the input as possible. Then you have to choose what the factorial function should do. One choice is to ignore the problem as it's not going to happen. The other is to check the parameter and return a special value if it's bad. This has the disadvantage that you have to check the function with several silly values, not just sensible ones.
Yes, I presumed the OP's post was just an example. Hopefully we've
provided food for thought  I've had some fun! :p

Rob  
P: n/a

In article <bE****************@news.optus.net.au>, RobG
<rg***@iinet.net.au> writes John G Harris wrote: In article <43**********************@perqv1newsreader01.iinet.net.au>, RobG <rg***@iinet.net.au> writes
John G Harris wrote:
In article <43***********************@perqv1newsreader01.iinet.net.au>, RobG <rg***@iinet.net.auau> writes <snip>
>1. What value should be returned for negative numbers? Probably null, >but maybe false or some error message? What should be done to >test/respond to noninteger values?
Recall that x! is defined for all real numbers, except that for 1, 2, 3, ... it goes off to +/ infinity (and drops down to nearly zero in between).
No, I don't  factorials are only defined for positive integers and zero, where 0! = 1. That's the schoolbook definition. In a serious textbook x! is defined as an integral, for any real x. The book then goes on to prove that (x+1)! = (x+1)*x and that 0! = 1. From this you can use a for loop to calculate 1!, 2!, 3!, ..., just as in a school textbook.
The 'schoolbook' definition is the formal definition of the factorial for natural numbers (including zero) which I think can be assumed unless something more complex is indicated.
As I said, 0.5! crops up in statistics when you want to know if your
experimental results support your case (or contradict someone else's
case).
The basic factorial function can be modified to estimate factorials for fractions, but I don't think that alters the above. I'd bee keen to see a JavaScript implementation of the factorial function for non integers. ;)
The modified function can be used to determine values for negative fractions but their behaviour is bizarre and as far as I can tell have no useful purpose  exactly what is complex negative infinity?
Every formal definition of a factorial I can find only relates to numbers greater than or equal to zero, so I'll continue to believe that n! is undefined where n<0.
The mathematics works, even if you don't have a use for it (yet).
The Wolfram Research page probably has more than any of us wishes to know:
<URL: http://mathworld.wolfram.com/Factorial.html >
Beware of the Wolfram web site. They concentrate on the definitions used
in their programming language. They don't always tell you about wider or
different definitions used elsewhere.
[...] I'm not the original poster so I don't know what's needed. My intention was to point out that the answer depends on the context. Ooops, sorry. I got my threads crossed. :x
For instance, if the context is statistical tests of significance then 0.5! is likely to crop up. On the other hand, if the context is combinations then both 0.5 and 0 are very likely to be errors.
In that case I'd try to avoid nonintegers, which should be possible in most cases.
Simplified functions can be defined for specific noninteger cases  a function that calculates halfinteger factorials is below (the error message could be more useful :) ):
function halfFactorial(n) { if ( n < 0  (n0.5) % 1) { return 'Only +ve halfintegers will do, e.g. 0.5, 3.5, etc.'; }
var rtPI = Math.sqrt(Math.atan(1)*4);
rtPI = Math.sqrt(Math.PI) is better. It uses a constant so is faster and
could well be more accurate.
var x=1; while (n>0){ x *= n; } return (rtPI*x).toFixed(2); }
Which gives:
0.5! = 0.89 1.5! = 1.33 2.5! = 3.32 3.5! = 11.63 4.5! = 52.34
But it should only be used for halves, not whole numbers and I have no idea what it would be useful for. A general solution for noninteger factorials written in JavaScript might be useful. :)
You need to find out how calculators do it, but the designers probably
don't want to tell you.
[...]
Obviously, silly values should be trapped as close to the input as possible. Then you have to choose what the factorial function should do. One choice is to ignore the problem as it's not going to happen. The other is to check the parameter and return a special value if it's bad. This has the disadvantage that you have to check the function with several silly values, not just sensible ones.
Yes, I presumed the OP's post was just an example. Hopefully we've provided food for thought  I've had some fun! :p
John

John Harris  
P: n/a

In article <xu**************@merlyn.demon.co.uk>, Dr John Stockton
<jr*@merlyn.demon.co.uk> writes JRS: In article <Xn********************@194.109.133.242>, dated Sat, 10 Dec 2005 09:02:54 local, seen in news:comp.lang.javascript, Evertjan. <ex**************@interxnl.net> posted :
it could be agued to prevent a too high n likewize:
function factorial(n) { return (n<2n>170)?1:n*factorial(n); } (a) ISTM that 1 should NOT be the result for an outofrange argument.
0 is available to indicate error as x! is nonzero for any real x.
<snip>function Factorial(n) { if (isNaN(n)) return NaN if (n<0) return NaN if (n>170) return Infinity if (n%1) return NaN return Fac(n) }
<snip>
This is javascript. Don't forget to test for no parameter, >1
parameters, and for the parameter type not being Number.
John

John Harris  
P: n/a

JRS: In article <11****************@PointedEars.de>, dated Mon, 12 Dec
2005 02:08:37 local, seen in news:comp.lang.javascript, Thomas
'PointedEars' Lahn <Po*********@web.de> posted : Dr John Stockton wrote:
[...] Thomas 'PointedEars' Lahn [...] posted : Dr John Stockton wrote: [...] Thomas 'PointedEars' Lahn [...] posted : > There are two approaches: iterative and recursive; the former > will allow you to calculate factorials of greater integers, of > course still with increasing loss of precision. Why do you say that? [...] Because how many recursive calls are possible, thus which is the greatest factorial that can be calculated through that approach, is limited by the range for IEEE doubles and the stack size; the greatest factorial that can be calculated through the iterative approach is only limited by the range for IEEE doubles.
You meant "... might allow your readers ...".
Pardon?
function Fac(m) { return m<2 ? 1 : m*Fac(m) }
Negative arguments should not return 1, and I would not want to rely on automatic semicolon insertion here.
You should have read my post dated Date: Sun, 11 Dec 2005 18:13:37 +0000
*before* considering my post dated Date: Sun, 11 Dec 2005 18:22:39 +0000
You might then have realised that Fac is not my suggested Factorial
function, but merely the recursive portion; I gave it to show exactly
what I tested on my system for recursion depth.
PKUATBT/KETFOB.

© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/jsindex.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.  
P: n/a

JRS: In article <bE****************@news.optus.net.au>, dated Mon, 12
Dec 2005 02:55:03 local, seen in news:comp.lang.javascript, RobG
<rg***@iinet.net.au> posted : var rtPI = Math.sqrt(Math.atan(1)*4);
or
var rtPI = Math.sqrt(Math.PI);

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

John G Harris wrote: In article <bE****************@news.optus.net.au>, RobG <rg***@iinet.net.au> writes
[...] The basic factorial function can be modified to estimate factorials for fractions, but I don't think that alters the above. I'd bee keen to see a JavaScript implementation of the factorial function for non integers. ;)
The modified function can be used to determine values for negative fractions but their behaviour is bizarre and as far as I can tell have no useful purpose  exactly what is complex negative infinity?
Every formal definition of a factorial I can find only relates to numbers greater than or equal to zero, so I'll continue to believe that n! is undefined where n<0.
The mathematics works, even if you don't have a use for it (yet).
Spoken like a mathematician... :p
[...] var rtPI = Math.sqrt(Math.atan(1)*4);
rtPI = Math.sqrt(Math.PI) is better. It uses a constant so is faster and could well be more accurate.
Yes [ACK to JRS too], hangover from some ported code from may old Sony
Pocket Computer  its BASIC didn't have PI.
[...] But it should only be used for halves, not whole numbers and I have no idea what it would be useful for. A general solution for noninteger factorials written in JavaScript might be useful. :)
You need to find out how calculators do it, but the designers probably don't want to tell you.
Here's one based on a version of Stirling's formula (wrapped for
posting) that seems good if rounded to an integer when n<6 or to 3 or 4
significant figures after that:
// n! = [(2*n + 1/3)*pi)^1/2] * (n/e)^n
function fractionFactorial(n)
{
return (Math.sqrt((2*n + 1/3)*Math.PI) *
Math.pow((n/Math.E),n)).toFixed(4);
}
[...]

Rob  
P: n/a

Dr John Stockton wrote: [...] Thomas 'PointedEars' Lahn [...] posted : Dr John Stockton wrote: [...] Thomas 'PointedEars' Lahn [...] posted : Dr John Stockton wrote: > [...] Thomas 'PointedEars' Lahn [...] posted : >> There are two approaches: iterative and recursive; the former >> will allow you to calculate factorials of greater integers, of >> course still with increasing loss of precision. > Why do you say that? [...] Because how many recursive calls are possible, thus which is the greatest factorial that can be calculated through that approach, is limited by the range for IEEE doubles and the stack size; the greatest factorial that can be calculated through the iterative approach is only limited by the range for IEEE doubles.
[1] You meant "... might allow your readers ...".Pardon?
function Fac(m) { return m<2 ? 1 : m*Fac(m) }
Negative arguments should not return 1, and I would not want to rely on automatic semicolon insertion here.
You should have read my post dated Date: Sun, 11 Dec 2005 18:13:37 +0000 *before* considering my post dated Date: Sun, 11 Dec 2005 18:22:39 +0000
I have.
You might then have realised that Fac is not my suggested Factorial function, but merely the recursive portion; I gave it to show exactly what I tested on my system for recursion depth.
OK, but that still does not explain what you mean with [1].
PKUATBT/KETFOB.
Whatever.
PointedEars  
P: n/a

On 20051212, John G Harris <jo**@nospam.demon.co.uk> wrote: As I said, 0.5! crops up in statistics when you want to know if your experimental results support your case (or contradict someone else's case).
yeah? I never encountered it, I only did stat101, what is the name of the
statistical test that used 0.5!
Bye.
Jasen  
P: n/a

JRS: In article <7w**************@jgharris.demon.co.uk>, dated Mon, 12
Dec 2005 20:52:06 local, seen in news:comp.lang.javascript, John G
Harris <jo**@nospam.demon.co.uk> posted : In article <xu**************@merlyn.demon.co.uk>, Dr John Stockton <jr*@merlyn.demon.co.uk> writesJRS: In article <Xn********************@194.109.133.242>, dated Sat, 10 Dec 2005 09:02:54 local, seen in news:comp.lang.javascript, Evertjan. <ex**************@interxnl.net> posted :
it could be agued to prevent a too high n likewize:
function factorial(n) { return (n<2n>170)?1:n*factorial(n); }
(a) ISTM that 1 should NOT be the result for an outofrange argument.
0 is available to indicate error as x! is nonzero for any real x.
Using 0 is OK if one is going to test the returned value (or a multiple
of it) each time; but it will not necessarily result in an obvious
effect in a general calculation. NaN is better for nonvalid values, or
possibly undefined  though I'd prefer to reserve that for variables
that have had nothing assigned to them.

© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/jsindex.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.   This discussion thread is closed Replies have been disabled for this discussion.   Question stats  viewed: 9427
 replies: 33
 date asked: Dec 9 '05
