I am trying to make a sequence of code that calculates the volume of a cone based on a user input height and radius (see below).
My problem is that the answer comes out wrong (but not by a long way). Using the example of height = 5, radius = 10, I get an answer from the code of 500 (treating pi as exactly 3), but calculating manually I get ~523.
I'm assuming it has something to do with the variable type I am declaring pi under (double then converting to long) but I have struggled to make any other combination of variable types work.
What is the correct version of this below that will store pi properly (to at least 5 or 6 dec places)?
double piDouble = Math.PI;
long height = Long.parseLong(heightString);
long pi = (new Double(piDouble)).longValue();
long radius = Long.parseLong(radiusString);
long volumeBase = (pi*(radius*radius)*height) / 3;
long pi = (new Double(piDouble)).longValue(); is a long, so it is equal to 3, exactly.
If you need more precision, use double all the way, and round at the end only. This should give you the result you expect:
double piDouble = Math.PI;
long height = Long.parseLong(heightString);
long radius = Long.parseLong(radiusString);
double volumeBase = (piDouble * (radius * radius) * height) / 3;
You can then round the result if you need to:
long roundedDownVolume = (long) volumeBase; //round down
long roundedVolume = Math.round(volumeBase); //or round to the closest long
You should use BigDecimal for this kind of arithmetic.
Related
I have a variable x that is 11.885, when I round this to 2 decimal points I want it to give me 11.88 but it won't work and I can't figure it out. I won't be using import or anything but just can't figure out a way to round this number down.
What I originally used:
double x = 11.885
double y = (double) Math.round(x * 100.0) / 100.0;
but this gives me 11.89. I also need this without printing it since I will be using this rounded number in my code.
Instead of Math.round(double), use Math.floor(double) like
double x = 11.885;
double y = Math.floor(x * 100) / 100.0;
System.out.println(y);
I get (as requested)
11.88
Try BigDecimal It has a lot of helpful features like this.
double x = 11.885;
BigDecimal y = BigDecimal.valueOf(x);
y.setScale(2, BigDecimal.ROUND_HALF_UP)
In Part 1 of a prompt, I am expected to integrate an equation into Java to get the value for a period (T). The equation is as follows: T = FS / (440 * (2 ^(h/12))
NOTE:
FS = sample rate, which is 44100 / 1.
h = halfstep, which is provided by the user.
An example of this equation is: 44100 / (440 * (2 ^(2/12)) = 89.3
The code I wrote is as follows:
public static double getPeriod(int halfstep) {
double T = 100; // TODO: Update this based on note
double FS = 44100 / 1;
double power = Math.pow(2, (halfstep / 12));
double denominator = 440 * (power);
double result = (FS) / (denominator);
T = Math.round(result);
return T;
}
// Equation test.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("halfstep is: ");
int halfstep = in.nextInt();
double period = getPeriod(halfstep);
System.out.print("Period: " + period + " ");
}
But when I run through this code with h = 2, T = 100.0 instead of the anticipated 89.3 and I am not sure what the issue is. Any thoughts on what's going on?
Because halfStep is an int, when you write
(halfstep / 12)
the calculation is done by taking halfStep / 12 and rounding down to the nearest integer. As a result, if you plug in 2 here, then halfStep / 12 will come back as 0 instead of 1/6. That's messing up the computation and is likely what's giving you the wrong answer.
You have a few options for how to proceed here. One would be to change halfStep to be a double rather than an int. Another would be to rewrite the division as
halfStep / 12.0
which, since 12.0 is a double literal, will perform the division in the way you intend.
One other potential issue - you declare the variable T as 100.0, but never use T anywhere in the calculation and ultimately overwrite it before returning it. I'm not sure whether this is intentional or whether that indicates that one of the formulas is incorrect.
Hope this helps!
my code:
long totalVolume = sellVolume + buyVolume;
float sellPercent = (float)(sellVolume / totalVolume);
float buyPercent = (float)(buyVolume / totalVolume);
All the variable are long in the first line of code, and then I am trying to calculate the Percentage of it.... but java returns me zero only ...
why is it so - Am i doing something wrong in typecasting
You should cast one of the operands to float before performing the division in order to perform floating point division (instead of long division).
float sellPercent = (float)sellVolume / totalVolume;
float buyPercent = (float)buyVolume / totalVolume;
I'm trying to make a program to simulate the solar system.
for(int i=0;i<1000;i++) {
double X=(160*Math.cos((2*PI*i)/365));
double Y=(160*Math.sin((2*PI*i)/365));
posX=Math.round(X);
posY=Math.round(Y);
cadre.repaint();
sleep(200);
}
f.setVisible(false);
To make my planets turning around the sun, I have a formula; the problem is that i have a double number with this formula, and i can't make him become an int (i tried floor(X), Math.round(X), doesn't work (error : incompatible types : possible lossy conversion from long to int)
[]
You'll see that it is not really java but he works as Java (it's some Javascool), so your advices will probably work for me!
When you convert a double to an int the compiler can't determine whether this is a safe operation or not. You have to use an explicit cast such as
double d = ...
int i = (int) d; // implicitly does a floor(d);
In Java 8 there is function to help detect whether the cast was safe (from a long at least) Math.toIntExact
int i = Math.toIntExact((long) d); // implicitly does a floor(d);
You can do this running the GUI Event Loop as a periodic task.
double X= 160*Math.cos(i * 2 * PI / 360);
double Y= 160*Math.sin(i * 2 * PI / 360);
posX = Math.toIntExact(Math.round(X));
posY = Math.toIntExact(Math.round(Y));
cadre.repaint();
// note you have to return so the image can actually be drawn.
Add cast to int like:
posX = (int) Math.round(X);
I'm trying to create a program in Java to calculate the inside angles of any triangle when the user inputs the side lengths. I've seen a few questions similar to this but I can`t get mine to work.
I want this to calculate the angle in degrees but it keeps giving me the wrong answer or not a number (NaN). I've tried putting it all in to one equation in case it was just rounding errors but it just gave the same answer. I've since put it back into this format to make it easier to read.
public class Triangles
{
// variables already declared and user inputs double sideOne, sideTwo, sideThree
threeSq=sideThree*sideThree;
twoSq=sideTwo*sideTwo;
oneSq=sideOne*sideOne;
public static double getAngleOne(double oneSq, double twoSq, double threeSq, double sideOne, double sideTwo, double sideThree)
{
double angOne;
angOne = (oneSq + twoSq - threeSq) / (2 * sideOne * sideTwo);
angOne = Math.toRadians(angOne);
angOne = Math.acos(angOne);
angOne = Math.toDegrees(angOne);
return angOne;
}
public static double getAngleTwo(double oneSq, double twoSq, double threeSq, double sideOne, double sideTwo, double sideThree)
{
double angTwo;
angTwo = (twoSq + threeSq - oneSq) / (2 * sideTwo * sideThree);
angTwo = Math.toRadians(angTwo);
angTwo = Math.acos(angTwo);
angTwo = Math.toDegrees(angTwo);
return angTwo;
}
public static double getAngleThree(double oneSq, double twoSq, double threeSq, double sideOne, double sideTwo, double sideThree)
{
double angThree;
angThree = (oneSq + threeSq - twoSq) / (2 * sideOne * sideThree);
angThree = Math.toRadians(angThree);
angThree = Math.acos(angThree);
angThree = Math.toDegrees(angThree);
return angThree;
}
}
I`m using the cosine law, but it is not giving me the correct answer. For example, when I input the side lengths as 3, 3 and 3 it gives me 71.68993312052173; when I input 5, 6 and 7 (sides 1, 2 and 3 respectively), I get NaN.
edit:
Thanks for the advice, I have changed all the ints to doubles and my math was the problem (forgot brackets around the oneSq + twoSq - threeSq)
I put up the full revised code but it is still giving the wrong answer, for a triangle with all sides the same, it should return 60 for all three but it`s returning 89.49999365358626.
After correcting the computation of the ratios there still remains one thing to do: Lose the lines
angOne = Math.toRadians(angOne);
at this point, angOne does not contain any angle. If the sides obey the triangle inequality, angOne should at that point contain a number between -1 and 1 that does not need converting.
The ratio of the areas for an equilateral triangle is 0.5. The operations convert-to-radians, acos, convert-to-degrees can be combined as
M*acos(x/M) = M*(pi/2-asin(x/M)),
with the multiplier M=180/pi. Since x/M is small, the result is approximately
M*(pi/2-x/M)=90-x,
resulting in a value close to 89.5, as obtained in your last trial.
Of course, the desired result is M*acos(0.5)=M*(pi/3)=60.
Apart from not using double values, your calculations are probably not correct.
According to cosine law
cosĪ³ = (a^2 + b^2 - c^2)/2ab
so change ang = oneSq + threeSq - twoSq / (2 * sideOne * sideThree); to
double ang = (oneSq + twoSq - threeSq)*1.0 / (2 * sideOne * sideTwo);