My value keeps showing up as NaN - java

Essentially my delta value is giving me some trouble, when I print all the variables to the console window everything is right and proper except for delta, whose value keeps showing up as NaN. I can't for the life of me figure out why. I am a beginning CIS student at a University and this is really giving me a headache.
import java.util.Scanner;
public class ReimannSumCalculator {
static double a,b,c,start,end;
static double partitions;
static double delta=end - start / partitions;
private static double Quadratic(double a,double b,double c,double x) {
double Quadratic = a*x*x + b*x + c;
return Quadratic;
}
public static void leftReiman(double a,double b,double c,double delta,double start,double end) {
double leftReiman = 0;
for(double x = start; x<end; x+=delta) {
leftReiman = delta * Quadratic(a,b,c,x) + leftReiman;
}
System.out.println("Your left Reiman sum is " + leftReiman);
}
public static void rightReiman(double a,double b,double c,double delta,double start,double end) {
double rightReiman = 0;
for(double x = start+delta; x<=end; x+=delta) {
rightReiman = delta* Quadratic(a,b,c,x) + rightReiman;
}
System.out.println("Your right Reiman sum is " + rightReiman);
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter some values for a b and c.");
a = keyboard.nextDouble();
b = keyboard.nextDouble();
c = keyboard.nextDouble();
System.out.println("Please enter a start and end point.");
start = keyboard.nextDouble();
end = keyboard.nextDouble();
System.out.println("Now enter the amount of partitions.");
partitions = keyboard.nextInt();
leftReiman(a,b,c,start,end,delta);
rightReiman(a,b,c,start,end,delta);
System.out.println("The delta is: " + delta);
System.out.println("The amount of partitions are: " + partitions);
System.out.println("a is: "+ a);
System.out.println("b is: "+ b);
System.out.println("c is: " + c);
System.out.println("The start is: " + start);
System.out.println("The end is: " + end);
}
}

You are executing start / partitions before you have initialized either one of these variables.
So you're essentially calculating 0.0/0.0, which equals NaN.

Java is not excel. It does not figure out the order of operations for a symbolic expression automatically, or recompute expressions when inputs change.
The burden of getting the order of operations right, and recomputing values when their inputs become stale is on the programmer.
static double a,b,c,start,end;
static double partitions;
static double delta=end - start / partitions;
is equivalent to
static double a,b,c,start = 0.0d, end = 0.0d;
static double partitions = 0.0d;
static double delta=end - start / partitions;
because all fields take on the zero value for their type, which is equivalent to
static double a,b,c,start = 0.0d, end = 0.0d;
static double partitions = 0.0d;
static double delta=0.0d - 0.0d / 0.0d; // division by zero -> NaN
because fields are initialized in the order of their declaration.
Then you fail to recompute delta in the body of main, so you end up passing a delta of NaN to leftReimann and rightReimann.
It might make sense to use an integer loop to make sure you deal with the right number of partitions instead of comparing a double x to double boundaries. Floating-point operations are lossy, so you can run into boundary conditions when checking doubles in your loop condition.
public static double leftReimann(double a,double b,double c,int partitions,double start,double end) {
assert partitions > 0;
double leftReimann = 0;
double delta = (end - start) / partitions;
for(int i = 0; i < partitions; ++i) {
double x = start + delta * i;
leftReimann += delta * Quadratic(a,b,c,x);
}
System.out.println("Your left Reimann sum is " + leftReimann);
return leftReimann;
}
public static double rightReimann(double a,double b,double c,int partitions,double start,double end) {
assert partitions > 0;
double rightReimann = 0;
double delta = (start - end) / partitions; // negative
for(int i = 0; i < partitions; ++i) {
double x = end + delta * i;
rightReimann += delta * Quadratic(a,b,c,x);
}
System.out.println("Your right Reimann sum is " + rightReimann);
return rightReimann;
}

There's two options, either make delta a function
private double getDelta() { return (end - start) / partitions;
or, you can recalculate delta after you set end, start, or partitions. (in this case, right before your calls to the Reiman functions, you should say:
delta = (end - start) / partitions;
so it uses the new values of end, start, and partitions.
As others have said, at the time you initialize delta, partitions is zero, so division by zero is NaN.

Related

java Sine(x) Taylor Series

Can someone help me for geting out this code of sin(x) Tailor function to get followings:
The first 4 sin(x) Tailor series.
To calculating the sin function using the sum-formel
How to write a method public static double MySinApproximate( double x)?
That is what i get so far, and it has to be in this way!!
import java.lang.Math;
public class mysin {
public static void main(String[] args){
double x= Math.PI;
System.out.println( MySin(x) + "\t \t" + Math.sin(x) + "\n" );
}
public static double MySin(double x){
double sumNeu, sumOld, sum;
int i = 1;
sum = sumNeu = x; // This should calculating the first term Value
do //the loop do will calculating the Tailor Series
{
sumOld = sumNeu;
i++; sum = + sum * x * x / i;
i++; sum = sum / i;
sumNeu = sumOld + sum;
}
while( sumNeu != sumOld);
return sumNeu;
}
} // 11.548739357257745 1.2246467991473532E-16 (as output)
Your loop isn't calculating the Taylor series correctly. (This is really a Maclaurin series, which is the special case of a Taylor series with a = 0.) For the sine function, the terms need to be added and subtracted in an alternating fashion.
sin(x) = x - x3/3! + x5/5! - ...
Your method only adds the terms.
sin(x) = x + x3/3! + x5/5! + ...
Flip the sign of sum on each iteration, by adding the designated line:
do // The loop will calculate the Taylor Series
{
sumOld = sumNeu;
i++; sum = + sum * x * x / i;
i++; sum = sum / i;
sum = -sum; // Add this line!
sumNeu = sumOld + sum;
}
With this change I get a result that is very close:
2.3489882528577605E-16 1.2246467991473532E-16
Due to the inherent inaccuracies of floating-point math in Java (and IEEE in general), this is likely as close as you'll get by writing your own sine method.
I tested an additional case of π/2:
System.out.println( MySin(x/2) + "\t \t" + Math.sin(x/2) + "\n" );
Again, it's close:
1.0000000000000002 1.0
1.I want to write all again like that -
2.I try to writing the first 4 series from sine Taylor and the proximity all together but anyhow doesn't work correctly -
3.i get this output
0.0 0.8414709848078965
0.8414709848078965 0.9092974268256817
0.8414709848078965 0.1411200080598672
0.9092974268256817 -0.7568024953079282
4.How can i get the same accuracy
1.0000000000000002 1.0
and the series of sine(x)?
public class MySin {
public static void main(String[] args){
double y = 0;
y = 4;
for (int i = 1; i<= y; i++){
System.out.println( MySin(i/2) + "\t \t" + Math.sin(i) + "\n" );
}
}
public static double MySin(double x){
double sumNew, sumOld, sum;
int i = 1;
sum = sumNew = x; // This should calculating the first term Value
do //the loop do will calculating the Tailor Series
{
sumOld = sumNew;
i++; sum = - sum * x * x / i; // i did change the sign to -
i++; sum = sum / i;
sum = - sum; // so i don't need this line anymore
sumNew = sumOld + sum;
}
while( sumNew != sumOld);
return sumNew;
}
public static double MySineProximity ( double x) {
while ( x <= ( Math.PI /2 ) )
{
x = 0;
}
return MySin (x);
}
}

Approximate a derivative for a continuous function throughout certain step intervals

I am looking to write a method in Java which finds a derivative for a continuous function. These are some assumptions which have been made for the method -
The function is continuous from x = 0 to x = infinity.
The derivative exists at every interval.
A step size needs to be defined as a parameter.
The method will find the max/min for the continuous function over a given interval [a:b].
As an example, the function cos(x) can be shown to have maximum or minimums at 0, pi, 2pi, 3pi, ... npi.
I am looking to write a method that will find all of these maximums or minimums provided a function, lowerBound, upperBound, and step size are given.
To simplify my test code, I wrote a program for cos(x). The function I am using is very similar to cos(x) (at least graphically). Here is some Test code that I wrote -
public class Test {
public static void main(String[] args){
Function cos = new Function ()
{
public double f(double x) {
return Math.cos(x);
}
};
findDerivative(cos, 1, 100, 0.01);
}
// Needed as a reference for the interpolation function.
public static interface Function {
public double f(double x);
}
private static int sign(double x) {
if (x < 0.0)
return -1;
else if (x > 0.0)
return 1;
else
return 0;
}
// Finds the roots of the specified function passed in with a lower bound,
// upper bound, and step size.
public static void findRoots(Function f, double lowerBound,
double upperBound, double step) {
double x = lowerBound, next_x = x;
double y = f.f(x), next_y = y;
int s = sign(y), next_s = s;
for (x = lowerBound; x <= upperBound ; x += step) {
s = sign(y = f.f(x));
if (s == 0) {
System.out.println(x);
} else if (s != next_s) {
double dx = x - next_x;
double dy = y - next_y;
double cx = x - dx * (y / dy);
System.out.println(cx);
}
next_x = x; next_y = y; next_s = s;
}
}
public static void findDerivative(Function f, double lowerBound, double
upperBound, double step) {
double x = lowerBound, next_x = x;
double dy = (f.f(x+step) - f.f(x)) / step;
for (x = lowerBound; x <= upperBound; x += step) {
double dx = x - next_x;
dy = (f.f(x+step) - f.f(x)) / step;
if (dy < 0.01 && dy > -0.01) {
System.out.println("The x value is " + x + ". The value of the "
+ "derivative is "+ dy);
}
next_x = x;
}
}
}
The method for finding roots is used for finding zeroes (this definitely works). I only included it inside my test program because I thought that I could somehow use similar logic inside the method which finds derivatives.
The method for
public static void findDerivative(Function f, double lowerBound, double
upperBound, double step) {
double x = lowerBound, next_x = x;
double dy = (f.f(x+step) - f.f(x)) / step;
for (x = lowerBound; x <= upperBound; x += step) {
double dx = x - next_x;
dy = (f.f(x+step) - f.f(x)) / step;
if (dy < 0.01 && dy > -0.01) {
System.out.println("The x value is " + x + ". The value of the "
+ "derivative is "+ dy);
}
next_x = x;
}
}
could definitely be improved. How could I write this differently? Here is sample output.
The x value is 3.129999999999977. The value of the derivative is -0.006592578364594814
The x value is 3.1399999999999766. The value of the derivative is 0.0034073256197308943
The x value is 6.26999999999991. The value of the derivative is 0.008185181673381337
The x value is 6.27999999999991. The value of the derivative is -0.0018146842631128202
The x value is 9.409999999999844. The value of the derivative is -0.009777764220086915
The x value is 9.419999999999844. The value of the derivative is 2.2203830347677922E-4
The x value is 12.559999999999777. The value of the derivative is 0.0013706082193754021
The x value is 12.569999999999776. The value of the derivative is -0.00862924258597797
The x value is 15.69999999999971. The value of the derivative is -0.002963251265619693
The x value is 15.70999999999971. The value of the derivative is 0.007036644660118885
The x value is 18.840000000000146. The value of the derivative is 0.004555886794943564
The x value is 18.850000000000147. The value of the derivative is -0.005444028885981389
The x value is 21.980000000000636. The value of the derivative is -0.006148510767989279
The x value is 21.990000000000638. The value of the derivative is 0.0038513993028788107
The x value is 25.120000000001127. The value of the derivative is 0.0077411191450771355
The x value is 25.13000000000113. The value of the derivative is -0.0022587599505241585
The main thing that I can see to improve performance in the case that f is expensive to compute, you could save the previous value of f(x) instead of computing it twice for each iteration. Also dx is never used and would always be equal to step anyway. next_x also never used. Some variable can be declare inside the loop. Moving the variable declarations inside improves readability but not performance.
public static void findDerivative(Function f, double lowerBound, double upperBound, double step) {
double fxstep = f.f(x);
for (double x = lowerBound; x <= upperBound; x += step) {
double fx = fxstep;
fxstep = f.f(x+step);
double dy = (fxstep - fx) / step;
if (dy < 0.01 && dy > -0.01) {
System.out.println("The x value is " + x + ". The value of the "
+ "derivative is " + dy);
}
}
}
The java code you based on (from rosettacode) is not OK, do not depend on it.
it's expecting y (a double value) will become exactly zero.
You need a tolerance value for such kind of tests.
it's calculating derivative, and using Newton's Method to calculate next x value,
but not using it to update x, there is not any optimization there.
Here there is an example of Newton's Method in Java
Yes you can optimize your code using Newton's method,
Since it can solve f(x) = 0 when f'(x) given,
also can solve f'(x) = 0 when f''(x) given, same thing.
To clarify my comment, I modified the code in the link.
I used step = 2, and got correct results.
Check how fast it's, compared to other.
That's why optimization is used,
otherwise reducing the step size and using brute force would do the job.
class Test {
static double f(double x) {
return Math.sin(x);
}
static double fprime(double x) {
return Math.cos(x);
}
public static void main(String argv[]) {
double tolerance = .000000001; // Our approximation of zero
int max_count = 200; // Maximum number of Newton's method iterations
/*
* x is our current guess. If no command line guess is given, we take 0
* as our starting point.
*/
double x = 0.6;
double low = -4;
double high = 4;
double step = 2;
int inner_count = 0;
for (double initial = low; initial <= high; initial += step) {
x = initial;
for (int count = 1; (Math.abs(f(x)) > tolerance)
&& (count < max_count); count++) {
inner_count++;
x = x - f(x) / fprime(x);
}
if (Math.abs(f(x)) <= tolerance) {
System.out.println("Step: " + inner_count + ", x = " + x);
} else {
System.out.println("Failed to find a zero");
}
}
}
}

Riemann Zeta Function in Java - Infinite Recursion with Functional Form

Note: Updated on 06/17/2015. Of course this is possible. See the solution below.
Even if anyone copies and pastes this code, you still have a lot of cleanup to do. Also note that you will have problems inside the critical strip from Re(s) = 0 to Re(s) = 1 :). But this is a good start.
import java.util.Scanner;
public class NewTest{
public static void main(String[] args) {
RiemannZetaMain func = new RiemannZetaMain();
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 <= 0)
System.out.println("Value for the Zeta Function = " + riemannFuncForm(s));
else if (s == 1)
System.out.println("The zeta funxtion is undefined for Re(s) = 1.");
else if(s >= 2)
System.out.println("Value for the Zeta Function = " + getStandardSum(s));
else
System.out.println("Value for the Zeta Function = " + getNewSum(s));
stop = System.currentTimeMillis();
totalTime = (double) (stop-start) / 1000.0;
System.out.println("Total time taken is " + totalTime + " seconds.");
}
// Standard form the 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;
}
public static double getStandardSum(double s){
return standardZeta(s);
}
//New Form
// zeta(s) = 2^(-1+2 s)/((-2+2^s) Gamma(1+s)) integral_0^infinity t^s sech^2(t) dt for Re(s)>-1
public static double Integrate(double start, double end) {
double currentIntegralValue = 0;
double dx = 0.0001d; // The size of delta x in the approximation
double x = start; // A = starting point of integration, B = ending point of integration.
// Ending conditions for the while loop
// Condition #1: The value of b - x(i) is less than delta(x).
// This would throw an out of bounds exception.
// Condition #2: The value of b - x(i) is greater than 0 (Since you start at A and split the integral
// up into "infinitesimally small" chunks up until you reach delta(x)*n.
while (Math.abs(end - x) >= dx && (end - x) > 0) {
currentIntegralValue += function(x) * dx; // Use the (Riemann) rectangle sums at xi to compute width * height
x += dx; // Add these sums together
}
return currentIntegralValue;
}
private static double function(double s) {
double sech = 1 / Math.cosh(s); // Hyperbolic cosecant
double squared = Math.pow(sech, 2);
return ((Math.pow(s, 0.5)) * squared);
}
public static double getNewSum(double s){
double constant = Math.pow(2, (2*s)-1) / (((Math.pow(2, s)) -2)*(gamma(1+s)));
return constant*Integrate(0, 1000);
}
// Gamma Function - 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;
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;
}
//Binomial Co-efficient - NOT CURRENTLY USING
/*
public static double binomial(int n, int k)
{
if (k>n-k)
k=n-k;
long b=1;
for (int i=1, m=n; i<=k; i++, m--)
b=b*m/i;
return b;
} */
// Riemann's Functional Equation
// Tried this initially and utterly failed.
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);
double nextTerm = Math.pow(2, (1-s))*Math.pow(Math.PI, (1-s)-1)*(Math.sin((Math.PI*(1-s))/2))*gamma(1-(1-s));
double error = Math.abs(term - nextTerm);
if(s == 1.0)
return 0;
else
return Math.pow(2, s)*Math.pow(Math.PI, s-1)*(Math.sin((Math.PI*s)/2))*gamma(1-s)*standardZeta(1-s);
}
}
Ok well we've figured out that for this particular function, since this form of it isn't actually a infinite series, we cannot approximate using recursion. However the infinite sum of the Riemann Zeta series (1\(n^s) where n = 1 to infinity) could be solved through this method.
Additionally this method could be used to find any infinite series' sum, product, or limit.
If you execute the code your currently have, you'll get infinite recursion as 1-(1-s) = s (e.g. 1-s = t, 1-t = s so you'll just switch back and forth between two values of s infinitely).
Below I talk about the sum of series. It appears you are calculating the product of the series instead. The concepts below should work for either.
Besides this, the Riemann Zeta Function is an infinite series. This means that it only has a limit, and will never reach a true sum (in finite time) and so you cannot get an exact answer through recursion.
However, if you introduce a "threshold" factor, you can get an approximation that is as good as you like. The sum will increase/decrease as each term is added. Once the sum stabilizes, you can quit out of recursion and return your approximate sum. "Stabilized" is defined using your threshold factor. Once the sum varies by an amount less than this threshold factor (which you have defined), your sum has stabilized.
A smaller threshold leads to a better approximation, but also longer computation time.
(Note: this method only works if your series converges, if it has a chance of not converging, you might also want to build in a maxSteps variable to cease execution if the series hasn't converged to your satisfaction after maxSteps steps of recursion.)
Here's an example implementation, note that you'll have to play with threshold and maxSteps to determine appropriate values:
/* Riemann's Functional Equation
* threshold - if two terms differ by less than this absolute amount, return
* currSteps/maxSteps - if currSteps becomes maxSteps, give up on convergence and return
* currVal - the current product, used to determine threshold case (start at 1)
*/
public static double riemannFuncForm(double s, double threshold, int currSteps, int maxSteps, double currVal) {
double nextVal = currVal*(Math.pow(2, s)*Math.pow(Math.PI, s-1)*(Math.sin((Math.PI*s)/2))*gamma(1-s)); //currVal*term
if( s == 1.0)
return 0;
else if ( s == 0.0)
return -0.5;
else if (Math.abs(currVal-nextVal) < threshold) //When a term will change the current answer by less than threshold
return nextVal; //Could also do currVal here (shouldn't matter much as they differ by < threshold)
else if (currSteps == maxSteps)//When you've taken the max allowed steps
return nextVal; //You might want to print something here so you know you didn't converge
else //Otherwise just keep recursing
return riemannFuncForm(1-s, threshold, ++currSteps, maxSteps, nextVal);
}
}
This is not possible.
The functional form of the Riemann Zeta Function is --
zeta(s) = 2^s pi^(-1+s) Gamma(1-s) sin((pi s)/2) zeta(1-s)
This is different from the standard equation in which an infinite sum is measured from 1/k^s for all k = 1 to k = infinity. It is possible to write this as something similar to --
// Standard form the 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;
}
The same logic doesn't apply to the functional equation (it isn't a direct sum, it is a mathematical relationship). This would require a rather clever way of designing a program to calculate negative values of Zeta(s)!
The literal interpretation of this Java code is ---
// Riemann's Functional Equation
public static double riemannFuncForm(double s) {
double currentVal = (Math.pow(2, s)*Math.pow(Math.PI, s-1)*(Math.sin((Math.PI*s)/2))*gamma(1-s));
if( s == 1.0)
return 0;
else if ( s == 0.0)
return -0.5;
else
System.out.println("Value of next value is " + nextVal(1-s));
return currentVal;//*nextVal(1-s);
}
public static double nextVal(double s)
{
return (Math.pow(2, s)*Math.pow(Math.PI, s-1)*(Math.sin((Math.PI*s)/2))*gamma(1-s));
}
public static double getRiemannSum(double s) {
return riemannFuncForm(s);
}
Testing on three or four values shows that this doesn't work. If you write something similar to --
// Riemann's Functional Equation
public static double riemannFuncForm(double s) {
double currentVal = Math.pow(2, s)*Math.pow(Math.PI, s-1)*(Math.sin((Math.PI*s)/2))*gamma(1-s); //currVal*term
if( s == 1.0)
return 0;
else if ( s == 0.0)
return -0.5;
else //Otherwise just keep recursing
return currentVal * nextVal(1-s);
}
public static double nextVal(double s)
{
return (Math.pow(2, s)*Math.pow(Math.PI, s-1)*(Math.sin((Math.PI*s)/2))*gamma(1-s));
}
I was misinterpretation how to do this through mathematics. I will have to use a different approximation of the zeta function for values less than 2.
I think I need to use a different form of the zeta function. When I run the entire program ---
import java.util.Scanner;
public class Test4{
public static void main(String[] args) {
RiemannZetaMain func = new RiemannZetaMain();
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 >= 2)
System.out.println("Value for the Zeta Function = " + getStandardSum(s));
else
System.out.println("Value for the Zeta Function = " + getRiemannSum(s));
stop = System.currentTimeMillis();
totalTime = (double) (stop-start) / 1000.0;
System.out.println("Total time taken is " + totalTime + " seconds.");
}
// Standard form the 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;
}
public static double getStandardSum(double s){
return standardZeta(s);
}
// Riemann's Functional Equation
public static double riemannFuncForm(double s, double threshold, double currSteps, int maxSteps) {
double term = Math.pow(2, s)*Math.pow(Math.PI, s-1)*(Math.sin((Math.PI*s)/2))*gamma(1-s);
//double nextTerm = Math.pow(2, (1-s))*Math.pow(Math.PI, (1-s)-1)*(Math.sin((Math.PI*(1-s))/2))*gamma(1-(1-s));
//double error = Math.abs(term - nextTerm);
if(s == 1.0)
return 0;
else if (s == 0.0)
return -0.5;
else if (term < threshold) {//The recursion will stop once the term is less than the threshold
System.out.println("The number of steps is " + currSteps);
return term;
}
else if (currSteps == maxSteps) {//The recursion will stop if you meet the max steps
System.out.println("The series did not converge.");
return term;
}
else //Otherwise just keep recursing
return term*riemannFuncForm(1-s, threshold, ++currSteps, maxSteps);
}
public static double getRiemannSum(double s) {
double threshold = 0.00001;
double currSteps = 1;
int maxSteps = 1000;
return riemannFuncForm(s, threshold, currSteps, maxSteps);
}
// Gamma Function - 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;
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;
}
//Binomial Co-efficient
public static double binomial(int n, int k)
{
if (k>n-k)
k=n-k;
long b=1;
for (int i=1, m=n; i<=k; i++, m--)
b=b*m/i;
return b;
}
}
I notice that plugging in zeta(-1) returns -
Enter the value of s inside the Riemann Zeta Function: -1
The number of steps is 1.0
Value for the Zeta Function = -0.0506605918211689
Total time taken is 0.0 seconds.
I knew that this value was -1/12. I checked some other values with wolfram alpha and observed that --
double term = Math.pow(2, s)*Math.pow(Math.PI, s-1)*(Math.sin((Math.PI*s)/2))*gamma(1-s);
Returns the correct value. It is just that I am multiplying this value every time by zeta(1-s). In the case of Zeta(1/2), this will always multiply the result by 0.99999999.
Enter the value of s inside the Riemann Zeta Function: 0.5
The series did not converge.
Value for the Zeta Function = 0.999999999999889
Total time taken is 0.006 seconds.
I am going to see if I can replace the part for --
else if (term < threshold) {//The recursion will stop once the term is less than the threshold
System.out.println("The number of steps is " + currSteps);
return term;
}
This difference is the error between two terms in the summation. I may not be thinking about this correctly, it is 1:16am right now. Let me see if I can think better tomorrow ....

Java calculate confidence interval

I'm looking for some method that takes or does not take parameters for calculate confidence interval.
I don't want the apache methods,
just a simple method or som type of code that does this.
My knowledge is restricted, it basically boils down to completing an online task against an expected set of answers (https://www.hackerrank.com/challenges/stat-warmup).
However, as far as I read up, there are mistakes in the given answer, and I'd like to correct these.
My source is pretty much wikipedia https://en.wikipedia.org/wiki/Confidence_interval#Basic_Steps
/**
*
* #return int[]{lower, upper}, i.e. int array with Lower and Upper Boundary of the 95% Confidence Interval for the given numbers
*/
private static double[] calculateLowerUpperConfidenceBoundary95Percent(int[] givenNumbers) {
// calculate the mean value (= average)
double sum = 0.0;
for (int num : givenNumbers) {
sum += num;
}
double mean = sum / givenNumbers.length;
// calculate standard deviation
double squaredDifferenceSum = 0.0;
for (int num : givenNumbers) {
squaredDifferenceSum += (num - mean) * (num - mean);
}
double variance = squaredDifferenceSum / givenNumbers.length;
double standardDeviation = Math.sqrt(variance);
// value for 95% confidence interval, source: https://en.wikipedia.org/wiki/Confidence_interval#Basic_Steps
double confidenceLevel = 1.96;
double temp = confidenceLevel * standardDeviation / Math.sqrt(givenNumbers.length);
return new double[]{mean - temp, mean + temp};
}
here is you go this is the code calculate Confidence Interval
/**
*
* #author alaaabuzaghleh
*/
public class TestCI {
public static void main(String[] args) {
int maximumNumber = 100000;
int num = 0;
double[] data = new double[maximumNumber];
// first pass: read in data, compute sample mean
double dataSum = 0.0;
while (num<maximumNumber) {
data[num] = num*10;
dataSum += data[num];
num++;
}
double ave = dataSum / num;
double variance1 = 0.0;
for (int i = 0; i < num; i++) {
variance1 += (data[i] - ave) * (data[i] - ave);
}
double variance = variance1 / (num - 1);
double standardDaviation= Math.sqrt(variance);
double lower = ave - 1.96 * standardDaviation;
double higher = ave + 1.96 * standardDaviation;
// print results
System.out.println("average = " + ave);
System.out.println("sample variance = " + variance);
System.out.println("sample standard daviation = " + standardDaviation);
System.out.println("approximate confidence interval");
System.out.println("[ " + lower + ", " + higher + " ]");
}
}

How can I modify my if statement so that the values print out after every full second?

So basically, I have a variable, time, and would like the program to print the other values for every full second.
For example if I plug in 100, it should print out 20 seconds only.
import java.util.Scanner;
public class CannonBlaster {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
final double DELTA_T = 0.01; //initiating all variables
final double G = 9.81;
double s = 0.0;
double time = 0.0;
double second = 0;
System.out.println("What's the initial velocity?: ");//asking for the initial velocity
double v =input.nextDouble();
while (s >= 0.0) //while loop is used. As long as the height isn't negative it will continue to go.
{
s += v * DELTA_T; //demonstrates the change of velocity and position for every .01 second.
v -= G * DELTA_T;
time += DELTA_T;
System.out.println("The time is: "+time+" "+(double) Math.floor(time)+" "+Math.round(time * 1000) / 1000);
second=Math.round(time * 1) / 1;
if ((double) Math.floor(time) ==time)
{
System.out.println("Approximated position: "+ s);
System.out.println("Formula's position: "+(100.0 * time - (time*time * G) / 2.0)); //prints out the formula values and the loop values.
}
}
}
Excuse the mess, it's just I've been trying different ways to get to work, but found none so far.
The problem is that double doesn't have the kind of accuracy you're looking for, so it doesn't count by an even .01 each iteration as your output clearly shows. The solution is to use BigDecimal. I rewrote the program a bit...
package test;
import java.math.BigDecimal;
import java.util.Scanner;
public class CannonBlaster {
private static final double G = 9.81;
private static final BigDecimal DELTA_T = new BigDecimal(0.01);
private static final double DELTA_T_DOUBLE = DELTA_T.doubleValue();
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double s = 0.0;
BigDecimal time = new BigDecimal(0.0);
double time_double = 0.0;
System.out.println("What's the initial velocity?: ");// asking for the
// initial
// velocity
double v = input.nextDouble();
// As long as the height isn't negative it will continue to go.
while (s >= 0.0)
{
s += v * DELTA_T_DOUBLE;
v -= G * DELTA_T_DOUBLE;
time = time.add(DELTA_T);
time_double = time.doubleValue();
if (time.doubleValue()%1==0) {
System.out.printf("Approximated position at t=%3ds is %10.6f.\n", time.intValue(), s);
// prints out the formula values and the loop values.
System.out.println("Formula's position: " + formula(time_double));
}
}
}
private static double formula(double x){
return 100.0 * x - (x * x * G) / 2.0;
}
}
The problem is that your time step, DELTA_T, is not exactly representable as a double value. Each iteration accumulates this small error, and you can see this in the time values that get printed out.
Usually it's preferable to avoid this problem when comparing two floating point numbers by comparing the absolute difference between the two numbers to some "small" value, where "small" is defined by the problem / magnitude of numbers you are working with. DELTA_T fits pretty well here, so you could use this comparison for a per-second time step:
if (Math.abs(time - Math.round(time)) < DELTA_T)
{
// Other code here
}
Alternatively, for a more generalized time step, in PRINT_INTERVAL:
final double PRINT_INTERVAL = 0.1;
// Other code...
if (Math.abs(time / PRINT_INTERVAL - Math.round(time / PRINT_INTERVAL)) < DELTA_T)
{
// Other code here
}

Categories