What is wrong in maclaurin series arccos calculations using java? - java

I am using mclaurins series to calculate arccos(x^2-1) but when i compare it to a result of math.acos it differs.
Here is my code:
public class Maclaurin {
public static int factorial(int fact) {
if(fact==0)
return 1;
return fact*factorial(fact-1);
}
public static void main(String[] args) {
int i, j;
double function = 0, x,result;
x=0;
for (int n = 0; n < 8; n++) {
function=((factorial(2*n))/(Math.pow(4, n)*Math.pow(factorial(n),2)*(2*n+1)))*Math.pow((Math.pow(x, 2)-1),2*n+1);
result=(Math.PI/2)-function;
System.out.println("x= "+x+" y= "+result);
System.out.println("Test "+Math.acos(Math.pow(x, 2)-1));
x+=0.13;
}
}
}
Programm output. test is a value calculated with Math.arccos and it differs from y calculated with mclaurins formula:
x= 0.0 y= 2.5707963267948966
Test 3.141592653589793
x= 0.13 y= 1.7291549939933966
Test 2.9574849820283498
x= 0.26 y= 1.6236496851024964
Test 2.771793621843802
x= 0.39 y= 1.5848621264898726
Test 2.5828078861333155
x= 0.52 y= 1.5725761587226181
Test 2.3885331918392687
x= 0.65 y= 1.5708496332463704
Test 2.1864594293995867
x= 0.78 y= 1.570796415168701
Test 1.9731661516473589
x= 0.91 y= 1.5707963267948972
Test 1.7435543826662978
EDIT:New code where calculations are in maclaurin function and i call it from main function. works good for all values except first 3:
package maclaurin;
public class Maclaurin {
private static double x;
//public static int factorial(int fact) {
// if(fact==0)
// return 1;
// return fact*factorial(fact-1);
//}
public static double factorial(int fact) {
if(fact==0)
return 1;
return fact*factorial(fact-1);
}
public static void main(String[] args)
{
x = 0;
for (int i=0;i<8;i++)
{
maclaurin(x);
x=x+0.14;
}
}
public static void maclaurin(double value){
double function = 0, x, result;
x =value;
for (int n = 0; n < 20; n++) {
function += ((factorial(2 * n)) / (Math.pow(4, n) * Math.pow(factorial(n), 2) * (2 * n + 1)))
* Math.pow((Math.pow(x, 2) - 1), 2 * n + 1);
}
result = (Math.PI / 2) - function;
System.out.println("x= " + x + " y= " + result);
System.out.println("Test " + Math.acos(Math.pow(x, 2) - 1));
}
}

The factorial of 16, which appears in your loop, is greater than MAX_INT.
I get:
>> factorial(16)
2.0923e+013
>> 2^31
2.1475e+009
in Octave. You need to do an analytic simplification to keep that in range or use double instead of int there.

I think you don't understand, what maclaurin series (taylor's series) is actually do. It can calculate an approximate value. You will get the exact value only for n -> ∞. Since we can't calculate that, we need to define some n and stop our calculation there. You have to add every single part of the summ to get the actual value. So basically you should iterate over n and ADD the calculated value to function and after the loop you can calculate result:
public static void main(String[] args){
double x = 0;
for(int i = 0;i < 8;i++){
System.out.println("x: " + x + " maclaurin: " + maclaurin(x));
System.out.println("Test: " + Math.acos(Math.pow(x, 2) - 1));
x += 0.14;
}
}
public static double maclaurin(double x){
double function = 0;
for (int n = 0; n < 10; n++) {
function += ((factorial(2 * n)) / (Math.pow(4, n) * Math.pow(factorial(n), 2) * (2 * n + 1)))
* Math.pow((Math.pow(x, 2) - 1), 2 * n + 1);
}
return (Math.PI / 2) - function;
}
this way I got pretty close values:
x: 0.0 maclaurin: 2.962490972738185
Test: 3.141592653589793
x: 0.14 maclaurin: 2.8972172328920296
Test: 2.9432779368601296
x: 0.28 maclaurin: 2.7366715068800485
Test: 2.7429790581451043
x: 0.42000000000000004 maclaurin: 2.5381695201901326
Test: 2.5385256934250617
x: 0.56 maclaurin: 2.3273181153351756
Test: 2.327323409412957
x: 0.7000000000000001 maclaurin: 2.105981109221438
Test: 2.1059811170704963
x: 0.8400000000000001 maclaurin: 1.8696239609917407
Test: 1.8696239609918046
x: 0.9800000000000001 maclaurin: 1.6104066839613247
Test: 1.6104066839613247
it seems, that result is not as good for x close to 0. You can increase n to get better results, but at some point you will get NaN, since factorial will overflow at some point.
don't forget to change factorial like #Brick suggested:
public static double factorial(int fact) {
if(fact==0)
return 1;
return fact*factorial(fact-1);
}
if you wonder how to calculate factorial in an iterative way, here is an example(it actually doesn't matter in this particular case, but hey, we are here to learn new things, right?):
public static double factorial(int fact) {
double result = 1;
while(fact > 1){
result *= fact--;
}
return result;
}
EDIT: changed fact parameter to int
EDIT2: wrapped maclaurin function and added more values
EDIT3: added iterative factorial

Related

Sin taylor series recursive approximation

I need some insight on my recursive method of calculating the sin Taylor series, which doesn't work properly. The method calls two other recursive methods which are a recursive pow method and a recursive factorial method. I compared my findings with an iterative sin method giving me the correct solution. What is missing in my recursive sin method ?
Approximation of sin(x)= x - x^3/3! + x^5/5! -x^7/7!+ ...
public class SinApprox
{
public static void main (String [] args)
{
Out.println(sinx(1, 1, 2, 1, 1, 0, 1));
Out.print(sinIT(2));
}
static double sinIT(double x)
{
double sin = 0;
double a = x;
double b = 1;
double term = a/b;
double vz = 1;
double i = 1;
while(term > 0.000001)
{
i = i +2;
sin = sin + (term*vz);
a= rekursivPow(x,i);
b = rekursivN(i);
term = a/b;
vz = -1 * vz;
}
return sin;
}
static double rekursivN(double n)
{
if(n==1)
{
return 1;
}
return n * rekursivN(n-1);
}
static double rekursivPow(double x , double y)
{
if(y == 1)
{
return x ;
}
return x * rekursivPow(x , y - 1);
}
static double sinx(double i ,double n, double x, double y, double vz, double sum, double pow)
{
double term = pow / n;
if(term > 0.000001)
{
sum = sum + (term * vz);
vz = -1 * vz;
i = i +2;
n = rekursivN(i);
y = y +2;
pow = rekursivPow(x ,y);
return sinx(i, n, x , y , vz, sum, pow);
}
return sum;
}
}
Step one would be to write out the function in a way that makes the recursive relationship clear (you can't write code for what isn't clear) so, don't start with this:
sin(x)= x - x^3/3! + x^5/5! -x^7/7!+ ...
But instead, ask "how can I make all those terms with x look the same":
sin(x)= x^1/1! - x^3/3! + x^5/5! + ...
Good start, but if we're recursing, what we're really looking for is something that only computes one of those terms, and then calls itself with updated arguments to compute the next term. Ideally, we want something like:
doThing(args) {
return simpleComputation() + doThings(updatedargs);
}
And then recursion does the rest. So let's first make sure that we only ever have to deal with + instead of a mix of + and -:
sin(x)= (-1)^0 * x^1/1! + (-1)^1 * x^3/3! + (-1)^2 * x^5/5! + ...
And now you have something you can actually express as a recursive relation, because:
sin(x,n) {
return (-1)^n * x^(2n+1) / (2n+1)! + sin(x, n+1);
}
With the "shortcut" function:
sin(x) {
return sin(x,0);
}
And that's where the hints stop, you should be able to implement the rest yourself. As long as you remember to stop the recursion because a Taylor series is infinite, and computer programs and resources are not.

Trying to calculate a factorial e^x, x being what the user enters, having trouble with the formula

I am in a Java class and it's still early in the class. The assignment is to:
e^x Approximations
The value ex can be approximated by the following sum:
1 + x + x^2/2! + x^3/3! + …+ x^n/n!
The expression n! is called the factorial of n and is defined as: n! = 1*2*3* …*n.
Write a program that takes a value of x as input and outputs four approximations of ex done using four different values of n: 5, 10, 50, and 100. Output the value of x the user entered and the set of all four approximations into the screen.
Sample formula use: calculating e^7 using approximation with n = 5
1 + 7 + 7^2/2! + 7^3/3! + 7^4/4! + 7^5/5!
I've got all the rest to work, including getting n to be 5, 10, 50 and 100. I thought I had the factorial formula figured out and I used the number 4 like the sample we were show and my numbers done match. Could really use another set of eyes.
Here's my code with forumla (x is the value the user enters and n is the 5, 10, 50 and 100):
/**
* myFact takes in x and calculates the factorial
* #param x
* #param n
* #return the factorial as a long
*/
public static long myFact(int x, int n) {
//declare variables
long sum = x;
for (int i=2; i <= n; i++) {
sum += ((Math.pow(x, i))/i);
}
return (sum + 1);
}
}
Here's the main class where I am calling the function. The error I suppose could be there too:
public static void main(String[] args) {
//declare variable for user input and call method to initialize it
int x = getNumber();
long fact;
int n;
//Output first line
System.out.println("N\t approximate e^" + x);
for (n = 5; n <= 100; n *= 2) {
if (n == 10) {
fact = myFact(x, n);
System.out.println(n + "\t " + fact);
n += 15;
} else {
fact = myFact(x, n);
System.out.println(n + "\t " + fact);
}
}
}
Thanks for taking a look at this, it's taken me hours to get this as the teacher gave us very little help.
You did a mistake in
sum += ((Math.pow(x, i))/i);
here you need to calculate the i!. Add below method in your code
public static int fact(int i){
int fact = 1;
for (int n = i; n > 0; n--) {
fact = fact * n;
}
return fact;
}
Also change sum += ((Math.pow(x, i))/i) to
sum += ((Math.pow(x, i))/fact(i));

Calculating PI with an special Algorithm

I have to calculate PI with this special algorithm for school:
pi = 4*(1/1 - 1/3 + 1/5 - 1/7 ... 1/n)
I've been trying a lot of things but it seems like I only get a never-ending loop because the condition for it is false, or my code is too complicated. The result I have to get is the calculated PI (only 6 decimals)=(the Algorithm for it).
Here's the code I've already tried:
public void PI()
{
double n=1.0;//while 3 counter
double z=1.0;//while 3 denominator
int i=0;//numerator for while 3
double pi=1.0;//Result
double x=0.0;//Calculated fractions
double y=1.0;//denominator for double x
double q=1; //Help for while 2
int f=0;//Help for while 3
while(new Double(Math.round(1000000.0*pi)).compareTo(new Double(Math.round(1000000.0*Math.PI)))==-1||new Double(Math.round(1000000.0*pi)).compareTo(new Double(Math.round(1000000.0*Math.PI)))==1) //while 1
{
while(new Double(Math.round(1000000.0*(4*x))).compareTo(new Double(Math.round(1000000.0*Math.PI)))==-1||new Double(Math.round(1000000.0*pi)).compareTo(new Double(Math.round(1000000.0*Math.PI)))==1)//while 2
{
if (q==1)
{
x+=0.1/y;
q++;
}
y+=2;
if(q==2)
{
x-=0.1/y;
q--;
}
y+=2;
i++;
}
pi=x*4.0;
}
while(f<=i)//while 3
{
System.out.println(n+"/"+z);
z+=2;
f++;
}
}
Your code looks overcomplicated. Try this:
/**
* Returns PI estimation based on equation:
* {#code PI' = 4*(1/1 - 1/3 + 1/5 - 1/7 ... 1/m)}
*
* #param n number of fractions in sum.
*/
public static double piEstimate(int n) {
double sum = 0;
for (int i = 0; i < n; i++) {
double fraction = (double) 1/(i*2+1);
int sign = (i % 2 == 0) ? 1 : -1;
sum += sign * fraction;
}
return 4*sum;
}
public static void main(String[] args) {
System.out.println("PI = " + piEstimate(10000));
}
you should add a System.out.println to see how the pi variable evolves in your second loop.

Java - Odd error message when converting double to BigDecimal

In a program, a double is being converted to BigDecimal. This returns a very strange error message.
public static double riemannFuncForm(double s) {
double term = Math.pow(2, s)*Math.pow(Math.PI, s-1)*
(Math.sin((Math.PI*s)/2))*gamma(1-s);
if(s == 1.0 || (s <= -1 && s % 2 == 0) )
return 0;
else if (s >= 0 && s < 2)
return getSimpsonSum(s);
else if (s > -1 && s < 0)
return term*getSimpsonSum(1-s);
else
return term*standardZeta(1-s);
}
BigDecimal val = BigDecimal.valueOf(riemannFuncForm(s));
System.out.println("Value for the Zeta Function = "
+ val.toEngineeringString());
This returns
Exception in thread "main" java.lang.NumberFormatException
What is causing this error message? Does BigDecimal.valueOf(double) not work correctly since this is referenced through another method?
Full program
/**************************************************************************
**
** Euler-Riemann Zeta Function
**
**************************************************************************
** XXXXXXXXXX
** 06/20/2015
**
** This program computes the value for Zeta(s) using the standard form
** of Zeta(s), the Riemann functional equation, and the Cauchy-Schlomilch
** transformation. A recursive method named riemannFuncForm has been created
** to handle computations of Zeta(s) for s < 2. Simpson's method is
** used to approximate the definite integral calculated by the
** Cauchy-Schlomilch transformation.
**************************************************************************/
import java.util.Scanner;
import java.math.*;
public class ZetaMain {
// Main method
public static void main(String[] args) {
ZetaMain();
}
// Asks the user to input a value for s.
public static void ZetaMain() {
double s = 0;
double start, stop, totalTime;
Scanner scan = new Scanner(System.in);
System.out.print("Enter the value of s inside the Riemann Zeta " +
"Function: ");
try {
s = scan.nextDouble();
}
catch (Exception e) {
System.out.println("You must enter a positive integer greater " +
"than 1.");
}
start = System.currentTimeMillis();
if (s == 1)
System.out.println("The zeta function is undefined for Re(s) " +
"= 1.");
else if (s < 2) {
BigDecimal val = BigDecimal.valueOf(riemannFuncForm(s));
System.out.println("Value for the Zeta Function = "
+ val.toEngineeringString());
}
else
System.out.println("Value for the Zeta Function = "
+ BigDecimal.valueOf(getStandardSum(s)).toString());
stop = System.currentTimeMillis();
totalTime = (double) (stop-start) / 1000.0;
System.out.println("Total time taken is " + totalTime + " seconds.");
}
// Standard form of the Zeta function.
public static double standardZeta(double s) {
int n = 1;
double currentSum = 0;
double relativeError = 1;
double error = 0.000001;
double remainder;
while (relativeError > error) {
currentSum = Math.pow(n, -s) + currentSum;
remainder = 1 / ((s-1)* Math.pow(n, (s-1)));
relativeError = remainder / currentSum;
n++;
}
System.out.println("The number of terms summed was " + n + ".");
return currentSum;
}
// Returns the value calculated by the Standard form of the Zeta function.
public static double getStandardSum(double s){
return standardZeta(s);
}
// Approximation of the Gamma function through the Lanczos Approximation.
public static double gamma(double s){
double[] p = {0.99999999999980993, 676.5203681218851,
-1259.1392167224028, 771.32342877765313,
-176.61502916214059, 12.507343278686905,
-0.13857109526572012, 9.9843695780195716e-6,
1.5056327351493116e-7};
int g = 7;
// Implements Euler's Reflection Formula.
if(s < 0.5) return Math.PI / (Math.sin(Math.PI * s)
*gamma(1-s));
s -= 1;
double a = p[0];
double t = s + g + 0.5;
for(int i = 1; i < p.length; i++){
a += p[i] / (s+i);
}
return Math.sqrt(2*Math.PI)*Math.pow(t, s+0.5)
*Math.exp(-t)*a;
}
/* Riemann's Functional Equation - Directly calculates the value of
Zeta(s) for s < 2.
1. The first if statement handles the case when s < 0 and s is a
multiple of 2k. These are trivial zeroes where Zeta(s) is 0.
2. The second if statement handles the values of 0 < s < 2. Simpson's
method is used to numerically compute an approximation of the
definite integral.
3. The third if statement handles the values of -1 < s < 0. Recursion
is used alongside an approximation through Simpson's method.
4. The last if statement handles the case for s <= -1 and is not a
trivial zero. Recursion is used directly against the standard form
of Zeta(s).
*/
public static double riemannFuncForm(double s) {
double term = Math.pow(2, s)*Math.pow(Math.PI, s-1)*
(Math.sin((Math.PI*s)/2))*gamma(1-s);
if(s == 1.0 || (s <= -1 && s % 2 == 0) )
return 0;
else if (s >= 0 && s < 2)
return getSimpsonSum(s);
else if (s > -1 && s < 0)
return term*getSimpsonSum(1-s);
else
return term*standardZeta(1-s);
}
// Returns the function referenced inside the right hand side of the
// Cauchy-Schlomilch transformation for Zeta(s).
public static double function(double x, double s) {
double sech = 1 / Math.cosh(x); // Hyperbolic cosecant
double squared = Math.pow(sech, 2);
return ((Math.pow(x, s)) * squared);
}
// Simpson's rule - Approximates the definite integral of f from a to b.
public static double SimpsonsRule(double a, double b, double s, int n) {
double simpson, dx, x, sum4x, sum2x;
dx = (b-a) / n;
sum4x = 0.0;
sum2x = 0.0;
// 4/3 terms
for (int i = 1; i < n; i += 2) {
x = a + i * dx;
sum4x += function(x,s);
}
// 2/3 terms
for (int i = 2; i < n-1; i += 2) {
x = a + i * dx;
sum2x += function(x,s);
}
// Compute the integral approximation.
simpson = function(a,s) + function(a,b);
simpson = (dx / 3)*(simpson + 4 * sum4x + 2 * sum2x);
return simpson;
}
// Handles the error for for f(x) = t^s * sech(t)^2. The integration is
// done from 0 to 100.
// Stop Simspson's Method when the relative error is less than 1 * 10^-6
public static double SimpsonError(double a, double b, double s, int n)
{
double futureVal;
double absError = 1.0;
double finalValueOfN;
double numberOfIterations = 0.0;
double currentVal = SimpsonsRule(a,b,s,n);
while (absError / currentVal > 0.000001) {
n = 2*n;
futureVal = SimpsonsRule(a,b,s,n);
absError = Math.abs(futureVal - currentVal) / 15;
currentVal = futureVal;
}
// Find the number of iterations. N starts at 8 and doubles
// every iteration.
finalValueOfN = n / 8;
while (finalValueOfN % 2 == 0) {
finalValueOfN = finalValueOfN / 2;
numberOfIterations++;
}
System.out.println("The number of iterations is "
+ numberOfIterations + ".");
return currentVal;
}
// Returns an approximate sum of Zeta(s) through Simpson's rule.
public static double getSimpsonSum(double s) {
double constant = Math.pow(2, (2*s)-1) / (((Math.pow(2, s)) -2)*
(gamma(1+s)));
System.out.println("Did Simpson's Method.");
return constant*SimpsonError(0, 100, s, 8);
}
}
Would I have to change all of my double calculations to BigDecimal calculations in order to fix this?
Nope. All you would need to do is to catch and handle the NumberFormatException appropriately. Or, test for NaN and Inf before attempting to convert the double.
In this case, you are only using BigDecimal for formatting in "engineering" syntax. So another alternative would be to do the formatting directly. (Though I haven't found a simple way to do that yet.)
This error occurs with you because BigDecimal.valueOf(value) does not accept "NaN" "Not a Number" as parameter and the following expression will return NaN
Math.pow(2, s)*Math.pow(Math.PI, s-1)*(Math.sin((Math.PI*s)/2))*gamma(1-s)
this Math.pow(2, s)*Math.pow(Math.PI, s-1)*(Math.sin((Math.PI*s)/2)) will evaluate -0.0
and this function gamma(1-s) will evaluate "Infinity"
So -0.0 * Infinity equal NaN in java
please see this to know When can Java produce a NaN.
When can Java produce a NaN?

How do I print the factorials of 0-30 on a table

public static void main(String[] args) {
int n = factorial(30);
int x = 0;
while (x <= 30) {
System.out.println(x + " " + n);
x = x + 1;
}
public static int factorial (int n) {
if (n == 0) {
return 1;
} else {
return n * factorial (n-1);
}
}
}
I'm trying to print out something like this:
0 1
1 1
2 2
3 6
4 24
...etc, up to 30 (30!)
What I'm getting instead is this:
0 (30!)
1 (30!)
...etc, up to 30
In words, I'm able to create the left column from 0 to 30 but I want to make it print the factorial of the numbers in the right hand column. With my code, it only prints the factorial of 30 in the right-hand column. I want it to print the factorials in order next to their corresponding number. How can I fix my code to do this?
This is pretty simple. Instead of defining a variable, you call the method with the updated x every time:
System.out.println(x + " " + factorial(x));
Note that your loop could be rewritten as a for loop, which is exactly what they're designed for:
for (int x = 0; x < 30; x++) {
System.out.println(x + " " + factorial(x));
}
Note a couple of things:
The x++. It's basically a short form of x = x + 1, though there are some caveats. See this question for more information about that.
x is defined in the loop (for (int x = ...) not before it
n is never defined or used. Rather than setting a variable that's only used once, I directly used the result of factorial(x).
Note: I'm actually pretty certain that an int will overflow when confronted with 30!. 265252859812191058636308480000000 is a pretty big number. It also overflows long, as it turns out. If you want to handle it properly, use BigInteger:
public BigInteger factorial(int n) {
if (n == 0) {
return BigInteger.ONE;
} else {
return new BigInteger(n) * factorial(n - 1);
}
}
Because of BigInteger#toString()'s magic, you don't have to change anything in main to make this work, though I still recommend following the advice above.
As #QPaysTaxes explains, the issue in your code was due to computing the final value and then printing it repeatedly rather than printing each step.
However, even that working approach suffers from a lack of efficiency - the result for 1 computes the results for 0 and 1, the result for 2 computes the results for 0, 1, and 2, the result for 3 computes the results for 0, 1, 2, and 3, and so on. Instead, print each step within the function itself:
import java.math.BigInteger;
public class Main
{
public static BigInteger factorial (int n) {
if (n == 0) {
System.out.println("0 1");
return BigInteger.ONE;
} else {
BigInteger x = BigInteger.valueOf(n).multiply(factorial(n - 1));
System.out.println(n + " " + x);
return x;
}
}
public static void main(String[] args)
{
factorial(30);
}
}
Of course, it would be faster and simpler to just multiply in the loop:
import java.math.BigInteger;
public class Main
{
public static void main(String[] args)
{
System.out.println("0 1");
BigInteger y = BigInteger.ONE;
for (int x = 1; x < 30; ++x) {
y = y.multiply(BigInteger.valueOf(x));
System.out.println(x + " " + y);
}
}
}
Just for fun, here's the efficient recursive solution in Python:
def f(n):
if not n:
print(0, 1)
return 1
else:
a = n*f(n-1)
print(n, a)
return a
_ = f(30)
And, better still, the iterative solution in Python:
r = 1
for i in range(31):
r *= i or 1
print(i, r)

Categories

Resources