BigInteger Java How To Recreate A Formula - java

I tried to recreate this formula i am sure it's correct but the problem it gives me infinity and i need your help to transform it to BigInteger please help if possible
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner Input = new Scanner(System.in);
double X = Input.nextDouble();
double Y = Input.nextDouble();
double Ans = 0;
for (int I = 1; I <= 20; I++) {
for (int J = 1; J <= 20; J++) {
Ans += Math.log10(1 + Math.exp(Math.pow(-1, I + J) * (((Math.pow(I, 2) * X)) + (Math.pow(J, 2)) * Y)));
}
}
System.out.println(Ans);
}
}

Related

What is wrong with my pi calculator?

I'm using Wallis' method to calculate pi, and I think I did it right. At least I thought I did anyway. I think the problem (output is 0)has to do with rounding and remainders, though I can't be sure. Here's the code:
import java.util.Scanner;
public class WallisPi {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a = 2;
int b = 3;
int c = 1;
int pi = 0;
double acc = 0.0;
int n = scan.nextInt();
scan.close();
for (int i = 0; i <= n; i++) {
pi = (2 / 3) * c;
if (a > b) {
b += 2;
} else {
a += 2;
}
c = a / b;
}
pi *= 4;
System.out.println("The approximation of pi is " + pi + ".");
acc = Math.PI - pi;
System.out.println("It is " + acc + " off.");
}
}
Since posting this I've made some changes to the code, though it's still not quite functional. I get 2.666..., so there's something else at work here as well.
import java.util.Scanner;
public class WallisPi {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double a = 2.0;
double b = 3.0;
double c = 1.0;
double pi = 0;
double acc = 0.0;
int n = scan.nextInt();
scan.close();
for (int i = 0; i <= n; i++) {
pi = (2.0 / 3.0) * c;
if (a > b) {
b += 2;
} else {
a += 2;
}
c = a / b;
}
pi *= 4;
System.out.println("The approximation of pi is " + pi + ".");
acc = Math.PI - pi;
System.out.println("It is " + acc + " off.");
}
}
int a=2;
int b=3;
double pi=2;
for(int i=0;i<=n;i++){
pi *= (double)a/(double)b;
if(a>b){
b+=2;
} else {
a+=2;
}
}
pi*=2;
Using n = 4000 yields 3.141200
Here's the whole program, fixed:
import java.util.Scanner;
public class WallisPi {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
scan.close();
double pi = 2;
int a = 2;
int b = 3;
for (int i = 0; i <= n; i++){
pi *= (double) a / (double) b;
if (a > b) {
b += 2;
} else {
a += 2;
}
}
pi *= 2;
double acc = Math.PI - pi;
System.out.println("The approximation of pi is " + pi + ".");
System.out.println("It is " + acc + " off.");
}
}
Since your varibles are ints, all your divisions are integer divisions, omitting the fraction (and preserving only the whole part of the result). For accurate results, you should define your variables as doubles:
double a=2;
double b=3;
double c=1;
double pi=0;

Pi with Nilakantha method

I am trying to calculate pi with the Nilakantha method. Whenever I run this program I get -Infinity if I input 1 and anything else I get NaN.
I am trying to modify my program that uses the Leibniz method, and I'm very new to java.
I appreciate all help!
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number of calculations you would like to do");
long no = Long.parseLong(reader.readLine());
long cycle = 0;
long w = 2;
long x = 3;
long y = 4;
long z = 4;
long odd=1;
long i=1;
long a = 1;
long b = 1;
double pi= 0.0;
for(;i<=no;i++)
{
a = w*x*y;
b = x*y*z;
double currentTerm=0.0;
if (i%2==0)
{
currentTerm=(double)4/a;
cycle = cycle+1;
w = w+1;
x = x+1;
y = y+1;
}
else
{
currentTerm=(double)-4/b;
cycle = cycle+1;
x = x+1;
y = y+1;
z = z+1;
}
odd=odd+2;
pi = pi+currentTerm;
}
System.out.println("You calculated that pi is");
System.out.println(pi);
System.out.println(3.1415926535897932);
System.out.println("Pi is actually");
double error = pi/3.1415926535897932;
if(error >= 1) {
double bigerror=2-error;
System.out.println("Your accuracy is");
System.out.println(bigerror*100);
System.out.println("percent");
System.out.println(cycle);
}
else {
System.out.println("Your accuracy is");
System.out.println(error*100);
System.out.println("percent");
System.out.println(cycle);
}
}
}
On your first iteration a and b are both zeros.
I don't think you have your initialization part correct.
http://helloacm.com/two-simple-equations-to-compute-pi/
Here I see that j starts from 2.
You have zeroes.
Make sure you implement the algorithm correctly.
Here is your code corrected.
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class MainProgram {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number of calculations you would like to do");
long no = Long.parseLong(reader.readLine());
long step = 0;
double ans = 3;
long j = 2;
double pi = 0.0;
while (true) {
step++;
if ((step % 2) == 1) {
ans += 4.0 / (1.0 * j * (j + 1) * (j + 2));
} else {
ans -= 4.0 / (1.0 * j * (j + 1) * (j + 2));
}
j += 2;
pi = ans;
if (step >= no)
break;
}
System.out.println("You calculated that pi is");
System.out.println(pi);
System.out.println("Pi is actually");
System.out.println(3.1415926535897932);
double error = pi / 3.1415926535897932;
if (error >= 1) {
double bigerror = 2 - error;
System.out.print("Your accuracy is: ");
System.out.print(bigerror * 100);
System.out.println(" percent");
System.out.println(step);
} else {
System.out.print("Your accuracy is: ");
System.out.print(error * 100);
System.out.println(" percent.");
System.out.println(step);
}
}
}

Adding last average value

I'm having trouble adding the last number of the loop that I have. I don't have any ideas how to include the last number and then add it to the double variable and then divide it to make the average. I would use my IDE to solve the problem but the input has to be approximately 1000 trials in order to be accurate. You can plainly see that 10 trials of 3.0 or higher does not equal approximately 2.8. I just need to have the missing trial added and then calculated into the average.
Code:
import java.util.*;
public class CalculatePI2
{
public static boolean ifitisInside (double xPosion, double yPosion)
{
double distance = Math.sqrt((xPosion * xPosion) + (yPosion * yPosion));
return (distance < 1.0);
}
public static double calculatePI (int numThrows)
{
Random randomGen = new Random();
int hits = 0;
double PI = 0;
double Alpha=0;
double average= 0;
for( int m=0; m<10; m++)
{
Alpha=+PI;
average= m/Alpha;
if(m>=0)
{
hits=0;
PI=0;
for (int i = 0; i <= numThrows; i++)
{
double xPosion = (randomGen.nextDouble()) * 2 - 1.0;
double yPosion = (randomGen.nextDouble()) * 2 - 1.0;
if (ifitisInside(xPosion, yPosion))
{
hits++;
double dthrows = numThrows;
PI =+ (4.0 * (hits/dthrows));
}
}
System.out.println("Trial["+m+"]: ="+ PI);
}
}
System.out.println("Estimate:"+average);
return PI;
}
public static void main (String[] args)
{
Scanner pie = new Scanner (System.in);
System.out.println("This program approximates PI using the Monte Carlo method. By simulating throwing darts at a dartboard. ");
System.out.print("Please enter number of throws: ");
int numThrows = pie.nextInt();
double PI = calculatePI(numThrows);
}
}
Just take the average computation out of the inner loop. Also, the loop invariant is from 0 to < numthrows, not <= numthrows. Also, your initialization of the variables needs to happen for each of your 10 trials, so it needs to be moved inside the loop.
double sumPiOverMTrials = 0;
for( int m=0; m<10; m++)
{
double hits = 0;
for (int i = 0; i < numThrows; i++) {
double xPosition = (randomGen.nextDouble()) * 2 - 1.0;
double yPosition = (randomGen.nextDouble()) * 2 - 1.0;
if (ifitisInside(xPosition, yPosition))
{
hits++;
}
}
double pi = 4.0 * hits/numthrows;
System.out.println("Trial["+m+"]: ="+ pi);
sumPiOverMTrials += pi;
}
System.out.println("Average over "+m+" trials ="+ sumPiOverMTrials/10);
I think you can solve this just by rearranging your code:
public static double calculatePI (int numThrows)
{
Random randomGen = new Random();
int hits = 0;
double PI = 0;
double Alpha=0;
double average= 0;
for( int m=0; m<10; m++)
{
for (int i = 0; i <= numThrows; i++)
{
double xPosion = (randomGen.nextDouble()) * 2 - 1.0;
double yPosion = (randomGen.nextDouble()) * 2 - 1.0;
if (ifitisInside(xPosion, yPosion))
{
hits++;
double dthrows = numThrows;
PI += (4.0 * (hits/dthrows)); // NOTE: += not =+
}
}
Alpha+=PI; // NOTE += not =+
average= m/Alpha;
if(m>=0)
{
hits=0;
PI=0;
}
System.out.println("Trial["+m+"]: ="+ PI);
}
}
This way the average is calculated after each trial rather than before. Also, I don't know much about this particular algorithm, but I think that this line:
average=m/Alpha;
should be:
average=Alpha/m

Decimal Format Issue Java

I wrote a program and I can't figure out how i should do the decimal format? I thought i was doing it right, apparently i can't do decimal format correctly. Can, someone help me with the decimal format?
Here is my code:
import java.text.DecimalFormat;
import java.util.*;
public class Mean {
public static void main(String [] args){
Scanner s = new Scanner(System.in);
double[]x = new double[10];
int i;
for(i = 0;i < 10; i++){
x[i] = s.nextDouble();
}
double mean = mean(x, i);
double deviation = var(x);
System.out.println("The mean is " + mean);
System.out.println("The standard deviation is " + deviation);
}
public static double sum(double[] a) {
double sum = 0.0;
for (int i = 0; i < a.length; i++) {
sum += a[i];
}
return sum;
}
public static double mean(double[]x, double i){
if (x.length == 0) return Double.NaN;
double sum = sum(x);
return sum / x.length;
}
public static double var(double[] x) {
if (x.length == 0) return Double.NaN;
double avg = mean(x, 10);
double sum = 0.0;
for (int i = 0; i < x.length; i++) {
sum += (x[i] - avg) * (x[i] - avg);
}
DecimalFormat myFormatter = new DecimalFormat("#,##0.00");
return sum / myFormatter.format(Math.sqrt(x.length - 1));
}
}
Try this to format your double(s)... I also had to update you method var -
public static String formatDouble(double in) {
DecimalFormat myFormatter = new DecimalFormat(
"#,##0.00");
return myFormatter.format(in);
}
public static double var(double[] x) {
if (x.length == 0)
return Double.NaN;
double avg = mean(x);
double sum = 0.0;
for (int i = 0; i < x.length; i++) {
sum += (x[i] - avg) * (x[i] - avg);
}
return sum / Math.sqrt(x.length - 1);
}
public static void main(String[] args) {
double[] x = new double[] {
2000.20, 1000.10, 3000.30, 4000.40,5000.50,
6000.60,7000,70,8000.80,9000.90
};
double mean = mean(x);
double deviation = var(x);
System.out.println("The mean is "
+ formatDouble(mean));
System.out.println("The standard deviation is "
+ formatDouble(deviation));
}
The problem is the formatter return a String. you should return a String in the metod signature
public static String var(double[] x)
Also this line
return sum / myFormatter.format(Math.sqrt(x.length - 1));
Will not work if you are to return a String. You should do the calculations first, and then format it. Then return the formatted number
Edit: Try this, see if it works
public static String var(double[] x) {
if (x.length == 0)
return null;
double avg = mean(x, 10);
double sum = 0.0;
for (int i = 0; i < x.length; i++) {
sum += (x[i] - avg) * (x[i] - avg);
}
DecimalFormat myFormatter = new DecimalFormat("#,##0.00");
double result = sum / Math.sqrt(x.length - 1);
return myFormatter.format(result);
}
Then where you have this double deviation = var(x); replace it with String deviation = var(x);
Edit 2: complete code
import java.text.DecimalFormat;
import java.util.*;
public class Mean {
public static void main(String [] args){
Scanner s = new Scanner(System.in);
double[]x = new double[10];
int i;
for(i = 0;i < 10; i++){
x[i] = s.nextDouble();
}
double mean = mean(x, i);
String deviation = var(x); // changed to String
System.out.println("The mean is " + mean);
System.out.println("The standard deviation is " + deviation);
}
public static double sum(double[] a) {
double sum = 0.0;
for (int i = 0; i < a.length; i++) {
sum += a[i];
}
return sum;
}
public static double mean(double[]x, double i){
if (x.length == 0) return Double.NaN;
double sum = sum(x);
return sum / x.length;
}
public static String var(double[] x) { // changed return
if (x.length == 0)
return null;
double avg = mean(x, 10);
double sum = 0.0;
for (int i = 0; i < x.length; i++) {
sum += (x[i] - avg) * (x[i] - avg);
}
DecimalFormat myFormatter = new DecimalFormat("#,##0.00");
double result = sum / Math.sqrt(x.length - 1);
return myFormatter.format(result);
}
}
Update: correct standard deviation formula
double result = Math.sqrt(sum / (x.length - 1));
^^
You need to format the double at the time of print.If you tried at var() function and then assign with double deviation then it will give numberformatException due to special character that returns by Var().You can run this code It will give you the output.
public static void main(String[] args) throws ParseException {
Scanner s = new Scanner(System.in);
double[]x = new double[10];
int i;
for(i = 0;i < 2; i++){
x[i] = s.nextDouble();
}
double mean = mean(x, i);
double deviation = var(x);
DecimalFormat myFormatter = new DecimalFormat("#,##0.00");
System.out.println("The mean is " + mean);
System.out.println("The standard deviation is " +myFormatter.format(deviation));
}
public static double sum(double[] a) {
double sum = 0.0;
for (int i = 0; i < a.length; i++) {
sum += a[i];
}
return sum;
}
public static double mean(double[]x, double i){
if (x.length == 0) return Double.NaN;
double sum = sum(x);
return sum / x.length;
}
public static double var(double[] x) {
if (x.length == 0) return Double.NaN;
double avg = mean(x, 10);
double sum = 0.0;
for (int i = 0; i < x.length; i++) {
sum += (x[i] - avg) * (x[i] - avg);
}
return sum / Math.sqrt(x.length - 1);
}

cos(x) program confusion with function input

How would I finish this program?
I know it is wrong where I have inputed the calculation into the code. What do I need to change to get the program to work the way the assignment asks (see image)? Also where would I loop it to recalculate if the user chooses to at the end?
package cosx;
import java.util.Scanner;
public class cosx2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the degree: ");
double degree = input.nextDouble();
double radian = getRadian(degree);
calculateCos(input, radian,degree);
}
public static double getRadian(double x) {
return x = (Math.PI/180)*x;
}
private static void calculateCos(Scanner std, double rad, double deg) {
System.out.print("How many terms do you want to calculate the cos: ");
int terms = std.nextInt();
double top;
double bottom;
double sum=0;
for(int i = 0; i<= terms; ++i){
top = Math.pow(-1, i);
bottom =1;
int repeat = 2*i+1;
for(int j = 1; j <= repeat; ++j){
bottom *= j;
}
if(i%2 == 0)
sum += (top/bottom);
else
sum -= (top/bottom);
}
System.out.printf("The sin (%.1f", deg);
System.out.printf(") is %.6f", sum);
}
}

Categories