473,406 Members | 2,336 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

factorial numbers in java script

hey guys, im just writing a basic calculation at the moment, before
building on it for an A-Level 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

Dec 9 '05 #1
33 9891
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

Dec 9 '05 #2
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

Dec 9 '05 #3
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 built-in 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 mark-up 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 e-mail.
Dec 9 '05 #4

patrick_woflian wrote:
hey guys, im just writing a basic calculation at the moment, before
building on it for an A-Level 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.

Dec 9 '05 #5
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 error-prone. Use spaces in tags only between element type
identifier and attribute-value-pairs. 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 side-effects.
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 http-equiv="Content-Script-Type" 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 built-in 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 side-effects with that feature.
}
[...]


Happy coding!
PointedEars
Dec 9 '05 #6
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
Dec 9 '05 #7
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

Dec 9 '05 #8
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(n-1) );
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 (x-y));

alert("THE ANSWER IS " + z);
//-->

</script>

<body>

</body>
any comments would be great..

Dec 9 '05 #9

patrick_woflian wrote:
function factorial(n) {
if ((n == 0) || (n == 1))
return 1
else {
var result = (n * factorial(n-1) );
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 semi-colon.
<script language = "javascript">
<!--
There is no need for SGML comments. The language attribute is
deprecated, use the type attribute instead:
z = (factorial x / factorial (x-y));


You have a syntax error. Fix it to be like so:

z = factorial(x) / factorial(x-y);

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.

Dec 9 '05 #10
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(n-1) );
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)

Dec 9 '05 #11
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/js-index.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/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Dec 9 '05 #12
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(n-1) );
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 non-recursive 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 non-integer values?

--
Rob
Dec 10 '05 #13
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 non-recursive 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<2||n>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 non-integer 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<1||n>170||Math.floor(n)!=n)?null:
(n<2)?1:n*factorial(--n);
}
--
Evertjan.
The Netherlands.
(Replace all crosses with dots in my emailaddress)

Dec 10 '05 #14
On 2005-12-09, 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/js-index.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: 10-11
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: 2-2
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: 10-11
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: 2-2
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: 10-11
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: 2-2
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: 10-11
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: 2-2
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: 10-11
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: 2-2
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: 10-11
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: 2-2
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: 10-11
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.sci-fi *****

Group othernet.fidonet.nz.sci-fi 2,2,2
state: 2-2
othernet.fidonet.nz.sci-fi 2 of 2 (from news.free.net.nz)
ff=0
downloaded othernet.fidonet.nz.sci-fi 2,2,2

**** SENDING othernet.fidonet.nz.sci-fi *****

Group othernet.fidonet.nz.sci-fi 11,11,11
state: 10-11
othernet.fidonet.nz.sci-fi 11 of 11 (from 127.0.0.1)
ff=0
downloaded othernet.fidonet.nz.sci-fi 11,11,11

**** RECIEVING alt.binaries.schematics.electronic *****

Group alt.binaries.schematics.electronic 1817,1817,1817
state: 437-1830
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:
Followup-To:

On 2005-12-09, 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/js-index.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: 10-11
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: 2-2
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: 10-11
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: 2-2
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: 10-11
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: 2-2
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: 10-11
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: 2-2
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: 10-11
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: 2-2
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: 10-11
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: 2-2
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: 10-11
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.sci-fi *****

Group othernet.fidonet.nz.sci-fi 2,2,2
state: 2-2
othernet.fidonet.nz.sci-fi 2 of 2 (from news.free.net.nz)
ff=0
downloaded othernet.fidonet.nz.sci-fi 2,2,2

**** SENDING othernet.fidonet.nz.sci-fi *****

Group othernet.fidonet.nz.sci-fi 11,11,11
state: 10-11
othernet.fidonet.nz.sci-fi 11 of 11 (from 127.0.0.1)
ff=0
downloaded othernet.fidonet.nz.sci-fi 11,11,11

**** RECIEVING alt.binaries.schematics.electronic *****

Group alt.binaries.schematics.electronic 1817,1817,1817
state: 437-1830
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:
Followup-To:

On 2005-12-09, 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/js-index.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: 10-11
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: 2-2
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: 10-11
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: 2-2
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: 10-11
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: 2-2
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: 10-11
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: 2-2
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: 10-11
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: 2-2
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: 10-11
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: 2-2
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: 10-11
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.sci-fi *****

Group othernet.fidonet.nz.sci-fi 2,2,2
state: 2-2
othernet.fidonet.nz.sci-fi 2 of 2 (from news.free.net.nz)
ff=0
downloaded othernet.fidonet.nz.sci-fi 2,2,2

**** SENDING othernet.fidonet.nz.sci-fi *****

Group othernet.fidonet.nz.sci-fi 11,11,11
state: 10-11
othernet.fidonet.nz.sci-fi 11 of 11 (from 127.0.0.1)
ff=0
downloaded othernet.fidonet.nz.sci-fi 11,11,11

**** RECIEVING alt.binaries.schematics.electronic *****

Group alt.binaries.schematics.electronic 1817,1817,1817
state: 437-1830
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:
Followup-To:

On 2005-12-09, 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/js-index.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
Dec 10 '05 #15
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
Dec 10 '05 #16
In article
<43***********************@per-qv1-newsreader-01.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 non-integer 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 non-integral values depends on the
customer's requirements.
alert("I don't do that");
is the simplest answer.

John
--
John Harris
Dec 10 '05 #17
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
Dec 10 '05 #18
John G Harris wrote:
In article
<43***********************@per-qv1-newsreader-01.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 non-integer 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 non-integral 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
Dec 10 '05 #19
In article
<43**********************@per-qv1-newsreader-01.iinet.net.au>, RobG
<rg***@iinet.net.au> writes
John G Harris wrote:
In article
<43***********************@per-qv1-newsreader-01.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 non-integer 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 school-book definition. In a serious text-book 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 text-book.

I suspect this is more than you really wanted to know :-)


Yes (see above).

What should be done for negative and non-integral 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
Dec 11 '05 #20
JRS: In article <439a1e2c$0$22292$5a62ac22@per-qv1-newsreader-
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 non-recursive 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 non-integer 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 non-negative, 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/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Dec 11 '05 #21
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<2||n>170)?1:n*factorial(--n);
}


(a) ISTM that 1 should NOT be the result for an out-of-range argument.

(b) ISTM that the tests should be inverted, so that a NaN argument
counts as out-of-range; 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 non-integer
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/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Dec 11 '05 #22
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/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Dec 11 '05 #23
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 2005-12-09, Dr John Stockton <jr*@merlyn.demon.co.uk> wrote:
<URL:http://www.merlyn.demon.co.uk/js-index.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 astron-1.htm, gravity0.htm ; quotings.htm, pascal.htm, etc.
No Encoding. Quotes before replies. Snip well. Write clearly. Don't Mail News.
Dec 11 '05 #24
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
Dec 12 '05 #25
John G Harris wrote:
In article
<43**********************@per-qv1-newsreader-01.iinet.net.au>, RobG
<rg***@iinet.net.au> writes
John G Harris wrote:
In article
<43***********************@per-qv1-newsreader-01.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 non-integer 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 school-book definition. In a serious text-book 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 text-book.


The 'school-book' 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 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 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 non-integers, which should be possible in
most cases.

Simplified functions can be defined for specific non-integer cases - a
function that calculates half-integer factorials is below (the error
message could be more useful :-) ):

function halfFactorial(n)
{
if ( n < 0 || (n-0.5) % 1) {
return 'Only +ve half-integers 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 non-integer
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
Dec 12 '05 #26
In article <bE****************@news.optus.net.au>, RobG
<rg***@iinet.net.au> writes
John G Harris wrote:
In article
<43**********************@per-qv1-newsreader-01.iinet.net.au>, RobG
<rg***@iinet.net.au> writes
John G Harris wrote:

In article
<43***********************@per-qv1-newsreader-01.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 non-integer 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 school-book definition. In a serious text-book 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 text-book.


The 'school-book' 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 non-integers, which should be possible in
most cases.

Simplified functions can be defined for specific non-integer cases - a
function that calculates half-integer factorials is below (the error
message could be more useful :-) ):

function halfFactorial(n)
{
if ( n < 0 || (n-0.5) % 1) {
return 'Only +ve half-integers 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 non-integer
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
Dec 12 '05 #27
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<2||n>170)?1:n*factorial(--n);
}
(a) ISTM that 1 should NOT be the result for an out-of-range argument.


0 is available to indicate error as x! is non-zero 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
Dec 12 '05 #28
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/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Dec 12 '05 #29
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 <= 4-line sig. separator as above, a line exactly "-- " (SonOfRFC1036)
Do not Mail News to me. Before a reply, quote with ">" or "> " (SonOfRFC1036)
Dec 12 '05 #30
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 non-integer
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
Dec 13 '05 #31
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
Dec 13 '05 #32
On 2005-12-12, 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
Dec 13 '05 #33
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> 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<2||n>170)?1:n*factorial(--n);
}


(a) ISTM that 1 should NOT be the result for an out-of-range argument.


0 is available to indicate error as x! is non-zero 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 non-valid 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/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Dec 13 '05 #34

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

Similar topics

5
by: kids_pro | last post by:
Hi there, I got the following code. int f = 1; int num =32767; while (num>0){ f = f * num; num --; }
35
by: aNt17017 | last post by:
This is my code: long fact(int n) { if (n == 0) return(1); if(n > 100) { printf("\t\tERROR: %d is too large for factorial.\n", n); return 1;
59
by: Umesh | last post by:
i wrote the following program to calculate factorial: #include<stdio.h> #include<iostream.h> void main() { int i,n; long int p=1; // or long double p=1; for exponential result which I don't...
3
by: Sugandh Jain | last post by:
Hi. How to write a function that will return me the factorial (say in a string) for the any positive integer it takes? When we find a factorial of even say 2000 or a higher number, it will be...
0
kadghar
by: kadghar | last post by:
Hi, I saw that Killer posted a simple Factorial Function that allows you to calculate up to 13!, well, you can use this for bigger numbers by changing the variable type. Why is this? You can...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.