Description
Compute the natural logarithm of the factorial of n .
License
Apache License
Parameter
Parameter | Description |
---|
n | Argument. |
Exception
Parameter | Description |
---|
NotPositiveException | if n < 0. |
Return
n!
Declaration
public static double factorialLog(final int n)
throws NotPositiveException
Method Source Code
/*/*from www . j a v a2 s.c o m*/
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.math.BigInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.commons.math3.exception.MathArithmeticException;
import org.apache.commons.math3.exception.NotPositiveException;
import org.apache.commons.math3.exception.NumberIsTooLargeException;
import org.apache.commons.math3.exception.util.Localizable;
import org.apache.commons.math3.exception.util.LocalizedFormats;
public class Main{
/** All long-representable factorials */
static final long[] FACTORIALS = new long[] { 1l, 1l, 2l, 6l, 24l,
120l, 720l, 5040l, 40320l, 362880l, 3628800l, 39916800l,
479001600l, 6227020800l, 87178291200l, 1307674368000l,
20922789888000l, 355687428096000l, 6402373705728000l,
121645100408832000l, 2432902008176640000l };
/**
* Compute the natural logarithm of the factorial of {@code n}.
*
* @param n Argument.
* @return {@code n!}
* @throws NotPositiveException if {@code n < 0}.
*/
public static double factorialLog(final int n)
throws NotPositiveException {
if (n < 0) {
throw new NotPositiveException(
LocalizedFormats.FACTORIAL_NEGATIVE_PARAMETER, n);
}
if (n < 21) {
return FastMath.log(FACTORIALS[n]);
}
double logSum = 0;
for (int i = 2; i <= n; i++) {
logSum += FastMath.log(i);
}
return logSum;
}
}
Related
- factorial(final int n)
- factorialDouble(final int n)