𝜋 = √12 × (1/1x30 - 1/3x31 + 1/5x32 - 1/7x33 +........)
I am trying to solve this equation using java but I do not know how to make subtract when the power is odd.
public static double calculatePiInnitial(int i){
double sum = 0;
for (int n=0; n<=i;n++){
for(int k = 1; k<=k; k =+ 2) {
if (n % 2 == 0)
sum += 1/k*Math.pow(3, n);
else
sum += -1/k* Math.pow(3, n);
}
}
System.out.println(sum);
final double SQRT_12 = Math.sqrt(12) ;
double Pi = SQRT_12 * sum;
return Pi ;
}
There are a couple of issues with the method that you have posted.
Firstly, you are attempting to initialize a variable in out update expression n++ int k=0, which is not valid syntax.
Even if the syntax allowed this, the update expression in not executed until after the body of the for loop, which means that k would not be accessible within the loop.
You should instead declare k together with n in you initialize expression. (also k should be initialized as 1 not 0)
Secondly, you are using i as the exponent when it should be n.
With these changes, you method becomes:
public static double calculatePiInnitial(int i){
double sum = 0;
for (int n=0, k = 1; n<=i; n++, k+=2){
if(n%2 == 0)
sum += 1/(k * Math.pow(3,n));
else
sum -= 1/(k * Math.pow(3,n));
}
System.out.println(sum);
final double SQRT_12 = Math.sqrt(12) ;
double Pi = SQRT_12 * sum;
return Pi ;
}
If you want to do this in two for loops , this is how it can be done. Here the inner for loop iterates only once.
public static double calculatePiInitial(int i){
double sum = 0;
for (int n=0; n<=i;n++){
for(int k = n*2+1; k < n*2+2; k++) {
if (n % 2 == 0)
sum += 1/(k*Math.pow(3, n));
else
sum += -1/(k* Math.pow(3, n));
}
}
System.out.println(sum);
final double SQRT_12 = Math.sqrt(12) ;
double Pi = SQRT_12 * sum;
return Pi ;
}
Hope it helps
Related
I don't know why x make an error which is in the array. -line 80,96
public static double naiveSine(double x, int n) {
//Implement this method
double sum;
double[][] NAIVE_SINE = new double[x][n];
if (n < 0) {
System.out.println("ERROR");
} else {
sum = 0;
for (int i = 1; i < n; i++) {
double term = 1;
for (int j = 1; j < 2*i - 1; j++){
term = term * (x/j);
}
if (i % 2 == 0) {
sum = sum - term;
} else {
sum = sum + term;
}
}
NAIVE_SINE[x][n] = sum;
}
return 0;
}
You cannot use doubles as indices for java primitive arrays.
double[][] NAIVE_SINE = new double[x][n];
x & n must be integers.
Your multi-dimensional array itself will store doubles but, not the indices. Below is an example of an array that would have dimensions 3x3.
1.0 1.1 1.2
1.1 1.2 1.3
1.2 1.3 1.4
There might be a way using the precision (max # of decimal places) of a double value to determine placement in a multi-dimensional array but, storing those values would not look pretty
I'm trying to create a Java program that will calculate a cosine value with the following equation:
The code to my program is located below. I don't appear to have any errors in my program however no matter what values that I set x and k to, I get the answer Infinity and I cannot figure out what I've done wrong.
The way that the code works, is that the console asks you for a value for x and then a value for k. Then the idea is to have Java compare the result of the equation (the method cosine in the script) with the Math.cos() function.
The method cosine is split up into two parts, cosinenumerator and cosinedenominator which is then divided with each other to become cosineresult at the end.
The loop for cosinedenominator is supposed to emulate a "factorial" in the equation.
Any help would be greatly appreciated.
import java.util.Scanner;
public class Cosine {
public static void main(String[] args) {
Scanner consolecosine = new Scanner(System.in);
System.out.println("Enter x value:");
double x = consolecosine.nextDouble();
System.out.println("Enter k value:");
int k = consolecosine.nextInt();
double cosineresult = cosine(x, k);
System.out.println("Using the Math.cos function yields: " + Math.cos(90));
System.out.println("Using the Taylor expansion equation yields: " + cosineresult);
}
public static double cosine(double x, int k) {
double cosineresult = 0;
double cosinenumerator = 0;
double cosinedenominator =0;
int i = 0;
int j = 0;
for(i = 0; i <= k; i++) {
cosinenumerator += Math.pow((-1),i) * Math.pow(x, (2*i));
}
for(j = 0; j <= (2*i); j++) {
cosinedenominator *= (2*j);
}
cosineresult = cosinenumerator / cosinedenominator;
return cosineresult;
}
}
Here's a working version (note that x is in radians; not degrees):
cosine(Math.PI, 15) yields -1.0000000000000002, which is about right.
public static double cosine(double x, int k) {
double cosineresult = 0;
double cosinedenominator = 1; // initial value 0! = 1; overflows at k = 86
int j = 2; // next multiplier in denominator factorial (skip 1)
for (int i = 0; i <= k; i++) {
double cosinenumerator = Math.pow((-1),i) * Math.pow(x, (2 * i));
// Continue calculation of factorial from last value
while (j <= 2 * i) {
cosinedenominator *= j++;
}
cosineresult += cosinenumerator / cosinedenominator;
}
return cosineresult;
}
I have to create classes to be implemented with the main class someone else has and for some reason I am not getting the right outputs, I'm not sure is my calculations are off which I don't think they are or my insert class is wrong.
Expected Output:
Median = 44.5
Mean = 49.300
SD = 30.581
Actual Output:
Median = 0.0
Mean = 0.967
SD = 4.712
public class StatPackage {
int count;
double [] scores;
final int MAX = 500;
StatPackage() {
count = 0;
scores = new double[MAX];
}
public void insert (double value) {
if (count < MAX){
scores[count] = value;
++ count;
}
}
public double Mean () {
double sum = 0;
//For loop for calculating average or mean
for(int i = 0; i < scores.length; i++){
sum += (scores[i]);
count++;
}
double average = sum/count;
return average;
}
public double Median() {
int min;
int tmp;
int size;
for (int i = 0; i < scores.length - 1; i ++)
{
min = i;
for (int pos = i + 1; pos < scores.length; pos ++)
if (scores [pos] < scores [min])
min = pos;
tmp = (int)scores [min];
scores [min] = scores [i];
scores [i] = tmp;
}
double median = 0;
if (scores.length % 2 == 0){
median = (scores[scores.length/2-1] + scores[scores.length/2])/2;
}
else {
median = (scores[((scores.length/2))]);
}
return median;
}
public double Variance () {
double variance = 0;
double sum = 0;
//For loop for getting the variance
for(int i = 0; i < scores.length; i++){
sum += scores[i];
variance += scores[i] * scores[i];
count++;
}
double varianceFinal = ((variance/count)-(sum*sum)/(count*count));
return (varianceFinal);
}
public double StdDev (double variance) {
double sum = 0;
for(int i = 0; i < scores.length; i++){
sum += scores[i];
variance += scores[i] * scores[i];
count++;
}
double varianceFinal = ((variance/count)-(sum*sum)/(count*count));
return Math.sqrt(varianceFinal);
}
}
The length of your scores array is 500, so every time you are using it in a calculation you are running that 500 times. You need to make your loop continuation conditions dependent on the number of values in the array, no the actual length of the array. I would be careful of your variable naming as well, you are using count in two places sometimes and it has global scope! This method stores the number of values in the array in the count variable:
public void insert (double value) {
if (count < MAX){
scores[count] = value;
++count;
}
}
So use the count variable as the loop-continuation condition when you are getting values from the array, like so:
public double mean() {
double sum = 0;
//For loop for calculating average or mean
for(int i = 0; i < count; i++){
sum += (scores[i]);
}
double average = sum / count;
return average;
}
That should help a little, I don't have time to check out your other methods but maybe this will give you a good starting place. I figured out what was happening by inserting print statements in your methods to make sure the values were as expected. It's a helpful thing to do when debugging. Your mean() method with the print statements looks like this:
public double mean() {
double sum = 0;
//For loop for calculating average or mean
for(int i = 0; i < count; i++){
sum += (scores[i]);
}
// print statements for debugging
System.out.println("count is " + count);
System.out.println("sum is " + sum);
double average = sum / count;
return average;
}
Because the solution is easily found by debugging, I will only give you a hint:
The mean of 3, 4 and 5 is 4: (3+4+5)/3, not (3+4+5)/(n*3) where
n is a positive integer.
If you look at your mean and std and divide it by the expected result, you will see it's a rounded number.
Once you find the solution to 1 problem, you will immediately know why the other results are faulty as well =)
The question here would be to get the sum of powers (m^0 + m^1 + m^2 + m^3.... + m^n) using only FOR loops. Meaning, not using any other loops as well as Math.pow();
Is it even possible? So far, I am only able to work around getting m^n, but not the rest.
public static void main(String[] args){
Scanner scn = new Scanner(System.in);
int total = 1;
System.out.print("Enter value of m: ");
int m = scn.nextInt();
System.out.print("Enter value of n: ");
int n = scn.nextInt();
for (int i = 1; i <= n; i++){
total * m;
}
System.out.print(total);
}
Let's say m =8; and n = 4;
i gives me '1,2,3,4' which is what I need, but I am unable to power m ^ i.
Would be nice if someone could guide me into how it could be done, can't seem to progress onwards as I have limited knowledge in Java.
Thanks in advance!
You might want to rewrite it like this :
m^0 + m^1 + m^2 + m^3.... + m^n = 1 + m * (1 + m * (1 + m * (.... ) ) )
And you do it in a single for loop.
This should do the job (see explanations in comments):
public long count(long m, int pow) {
long result = 1;
for(int i = 0;i<pow; i++) {
result*=m +1;
}
return result;
}
You can nest loops. Use one to compute the powers and another to sum them.
You can do below:
int mul = 1;
total = 1;
for(int i=1;i<=n;i++) {
mul *= m;
total += mul;
}
System.out.println(total);
You can use a single loop which is O(N) instead of nested loops which is O(N^2)
long total = 1, power = m
for (int i = 1; i <= n; i++){
total += power;
power *= m;
}
System.out.print(total);
You can also use the formula for geometric series:
Sum[i = k..k+n](a^i) = (a^k - a^(k+n+1)) / (1 - a)
= a^k * (1 - a^(n+1)) / (1 - a)
With this, the implementation can be done in a single for loop (or 2 simple for loop): either with O(n) simple looping, or with O(log n) exponentiation by squaring.
However, the drawback is that the data type must be able to hold at least (1 - a^(n+1)), while summing up normally only requires the result to fit in the data type.
This is the solution :
for(int i=0;i<n;i++){
temp=1;
for(int j=0;j<=i;j++){
temp *= m;
}
total += temp;
}
System.out.println(total+1);
You can easily calculate powers using your own pow function, something like:
private static long power(int a, int b) {
if (b < 0) {
throw new UnsupportedOperationException("Negative powers not supported.");
}
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
return a * power(a, b - 1);
}
Then simply loop over all the values and add them up:
long out = 0;
for (int i = 0; i <= n; ++i) {
out += power(m, i);
}
System.out.println(out);
I would add that this is a classic dynamic programming problem as m^n is m * m^(n-1). I would therefore add caching of previously calculated powers so that you don't have to recalculate.
private static Map<Integer, Long> powers;
public static void main(String args[]) {
int m = 4;
int n = 4;
powers = new HashMap<>();
long out = 0;
for (int i = 0; i <= n; ++i) {
out += power(m, i);
}
System.out.println(out);
System.out.println(powers);
}
private static long power(int a, int b) {
if (b < 0) {
throw new UnsupportedOperationException("Negative powers not supported.");
}
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
Long power = powers.get(b);
if (power == null) {
power = a * power(a, b - 1);
powers.put(b, power);
}
return power;
}
This caches calculated values so that you only calculate the next multiple each time.
How do I divide a large positive integer n into m parts uniformly randomly.
Post-condition: Adding up all the m parts should give n.
Below is my attempt(in java like pseudocode), but I don't think it will give me uniformly random distribution.
I am first finding the average part avg by dividing n/m. Then I am generating m-1 random numbers which are around avg in magnitude(by alternately generating random numbers between 0 & avg, and *avg & 2*avg*. Then I am subtracting the sum of these m-1 numbers from original number n and setting that as the m'th part.
Assume that the function rand(x, y) returns a random number uniformly between x and y.
int[] divideUniformlyRandomly(int n, int m)
{
int[] res = new int[m];
int avg = n / m;
int sum = 0;
bool alternator = false;
for(int i = 0; i < m - 1; i++)
{
if(alternator == false)
{
res[i] = rand(0, avg);
alternator = true;
}
else
{
res[i] = rand(avg, 2*avg);
alternator = false;
}
sum += res[i];
}
res[m-1] = n - sum;
return res;
}
public double[] divideUniformlyRandomly(double number, int part) {
double uniformRandoms[] = new double[part];
Random random = new Random();
double mean = number / part;
double sum = 0.0;
for (int i=0; i<part / 2; i++) {
uniformRandoms[i] = random.nextDouble() * mean;
uniformRandoms[part - i - 1] = mean + random.nextDouble() * mean;
sum += uniformRandoms[i] + uniformRandoms[part - i -1];
}
uniformRandoms[(int)Math.ceil(part/2)] = uniformRandoms[(int)Math.ceil(part/2)] + number - sum;
return uniformRandoms;
}
You should divide n in m parts using m - 1 uniformy distributed fences. Your code could be :
int[] divideUniformlyRandomly(int n, int m)
{
int[] fences = new int[m-1];
for(int i = 0; i < m - 2; i++)
{
fences[i] = rand(0, n-1);
}
Arrays.sort(fences);
int[] result = new int[m];
result[0] = fences[0];
for(int i = 1; i < m - 2; i++)
{
result[i] = fences[i+1] - fences[i];
}
result[m-1] = n - 1 - fences[m-2];
return result;
}
To illustrate this :