Cannot figure out why i'm getting a null value in calculation - java

So essentially this is a simple loop that should add up for 10 seconds the distance fallen for an object. When I was debugging it I saw it passed and the variables with correct values but when I entered a println statement right after the calculation in my fallingDistance method, the variable "distance" had a value of zero which I do not see how is possible. What am I missing here?
import java.lang.Math;
import javax.swing.JOptionPane;
public class FallingDistance {
public static void main(String[] args) {
double distance =0;
int count = 0;
double distanceCalc = 0;
int varTime = 0;
while (varTime < 10) {
varTime += 1;
System.out.println(varTime);
fallingDistance(varTime);
distanceCalc += distance;
JOptionPane.showMessageDialog(null, "The distance travelled is " + distanceCalc + " meters.");
}
}
public static double fallingDistance(int varTime) {
double gravity = 9.8;
double distance = Math.pow(((1 / 2) * gravity * varTime), 2);
System.out.println(gravity);
return distance;
}
}

You must assign value to the distance before using it in main!
public class FallingDistance {
public static void main(String[] args) {
double distance =0;
int count = 0;
double distanceCalc = 0;
int varTime = 0;
while (varTime < 10) {
varTime += 1;
System.out.println(varTime);
distance = fallingDistance(varTime);
distanceCalc += distance;
JOptionPane.showMessageDialog(null, "The distance travelled is " + distanceCalc + " meters.");
}
}
public static double fallingDistance(int varTime) {
double gravity = 9.8;
double distance = Math.pow(((double)(1 / 2) * gravity * varTime), 2);
System.out.println(gravity);
return distance;
}

Please assign the value returned from fallingDistance(varTime) method to distance.
Your while loop should be rewritten as:
while (varTime < 10) {
varTime += 1;
System.out.println(varTime);
distance = fallingDistance(varTime);
distanceCalc += distance;
JOptionPane.showMessageDialog(null, "The distance travelled is " + distanceCalc + " meters.");
}
Also, your 1/2 will always be evaluated to 0 (because its evaluated as integer). The fallingDistance() method should be rewritten as:
public static double fallingDistance(int varTime) {
double gravity = 9.8;
double distance = Math.pow((0.5 * gravity * varTime), 2);
System.out.println(gravity);
return distance;
}

Related

Converting to a fraction

Trying to convert a decimal into a fraction and provide its reciprocal
This is for Java. I tried multiple methods and doing a Math.pow, it is a bit complicated when I already have the answer in decimal form only want to convert it and have the program give the reciprocal
public class ParallelSeriesCircuit {
public static final int SERIES = 1;
public static final int PARALLEL = 2;
public int circuitType;
public double[] resistance;
public double Rtotal;
public int Rseries;
public int getNumberOfResistors() {
return resistance.length;
}
public double getTotalResistance() {
if (circuitType == SERIES) {
return getSeriesResistance();
} else {
return getParallelResistance();
}
}
public double getParallelResistance() {
int i = 0;
for (i = 0; i < resistance.length; i++) {
Rtotal += 1 / resistance[i];
}
return Rtotal;
}
private double getSeriesResistance() {
for (int i = 0; i < resistance.length; i++) {
Rtotal += resistance[i];
}
return Rtotal;
}
}
The problem lies in method getParallelResistance as I can't seem to figure out a conversion to a fraction. This is based on user input so that makes it even more complicated
Formula for Series Resistance is R = R1 + R2 + R3 + ... and is correctly calculated by getSeriesResistance().
Formula for Parallel Resistance is 1 / R = 1 / R1 + 1 / R2 + 1 / R3 +... but that is not what getParallelResistance() calculates.
Change to return 1 / Rtotal;
Also, you need to make Rtotal a local variable:
public double getParallelResistance() {
double sum = 0;
for (double r : resistance) {
sum += 1 / r;
}
return 1 / sum;
}
private double getSeriesResistance() {
double sum = 0;
for (double r : resistance) {
sum += r;
}
return sum;
}

JAVA Looping a formula

To start, I'm a relatively new programmer as it pertains to JAVA. I've searched for many things but it's possible I'm not search for the right thing. I'm basically trying to list from the first "year" to the 10th "year" a starting amount, multiplied by the percentage, and added to the starting amount. Then, I want to take that new amount and do the same thing over and over again until it gets to 10. Or, even a specified total ex:2000.
public static void main(String[] args)
{
double startAmount = 1000;
double ratePercentage = 0.05;
double newAmount;
for (int i = 0; i <= 10; i++){
newAmount = startAmount + (startAmount * ratePercentage);
System.out.println(i + " " + newAmount);
}
}
I'm not 100% sure what you are trying to achive. But assuming you are trying to do some sort of compounding interest. This should help.
public static void main(String[] args)
{
double startAmount = 1000;
double ratePercentage = 0.05;
double newAmount;
newAmount = startAmount;
for (int i = 0; i <= 10; i++){
newAmount = newAmount + (newAmount * ratePercentage);
System.out.println(i + " " + newAmount);
}
}
Try this
public static void main(String[] args)
{
double startAmount = 1000;
double ratePercentage = 0.05;
double newAmount;
for (int i = 0; i < 10; i++){
newAmount = startAmount + (startAmount * ratePercentage);
System.out.println(i + " " + newAmount);
startAmount=newAmount;
}
}

Sin approximation using Maclaurin expansion

I'm trying to write own code for calculating approximation of rad angle. I works so far for only a specific range of numbers, but fails for large ones like 500 or so.
Additional subquestion: which is more efficient - calculating powers by Math.pow() or the current way of doing it - only multiplication operators.
private static double sin_range(double rad) {
double sin_rad = rad;
while (sin_rad > 2 * Math.PI) {
sin_rad -= 2 * Math.PI;
}
return sin_rad;
}
private static double approx(double rad, int err) {
double rad_in_range = sin_range(rad);
double sin = rad_in_range, r = rad_in_range;
int previous = 1, factorial = 1;
for (int i = 0; i < err; i++) {
factorial = (factorial * (previous + 1) * (previous + 2));
r *= rad * rad;
if ((i & 1) == 0) { //even
sin -= r / factorial;
} else { //odd
sin += r / factorial;
}
previous += 2;
}
return sin;
}
public static void main(String[] args) {
double approximated = approx(15, 5);
System.out.println(approximated + " = " + Math.sin(15));
}

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;

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

Categories