Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am new to object and classes. I am creating this test program to get the area of the triangle. I kept getting 0 as the area. I have no idea where did I get it wrong.
public class Project1 {
public static void main(String args[]) {
Triangle triangle1 = new Triangle();
System.out.println("The area of the triangle with base "
+ triangle1.base + "and with width "
+ triangle1.width + " is " + triangle1.getArea());
}
}
class Triangle {
double base = 1.0;
double width = 1.0;
double getArea() {
return 1 / 2 * base * width;
}
}
Change the following
double getArea() {
return 1/2 * base * width;
}
To
double getArea() {
return 0.5 * base * width;
}
Due to integer division 1/2 yields 0.
try to use double numbers at getArea() method something like this:
double getArea() {
return 1.0 / 2.0 * base * width;
}
Explanation
You are computing 1 / 2.
This is integer division which does not support decimal values. It always rounds towards zero, the result is thus
1 / 2 = 0
Because of that the computation gets 0 too.
Solution
You can fix it by dividing decimal values instead of integers:
return 1.0 / 2.0 * base * width;
There is no integer division as soon as one of the operands is a decimal value like a double or float. You indicate double by adding the dot like 2.0.
Alternatively you could use the decimal value 0.5 right from the start:
return 0.5 * base * width;
Note that both versions are equally fast since the compiler will pre-compute such constant computations at compile-time. The bytecode will thus have 0.5 for both versions.
It is very common mistake for Java beginners, and I admit I sometimes still make this mistake. When divide one integer by another integer in Java, the result will be an integer as well. So while you expect 1 / 2 will be 0.5, the result will be 0 (i.e. it is truncated). You could cast the number first to force the division to use float or double like:
1 / (float) 2
1 / (double) 2
Or use the shorthand:
1 / 2f
1 / 2d
where f cast the number before it to float, and d to double.
Related
This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 11 months ago.
I'm trying to code an implementation of the fixed iteration algorithm in java - using java because that's what I'm most comfortable with at the moment, although I imagine that there'd be languages more suited to this purpose than java.
My base function is f(x) = x^4 + 2x^2 - x - 3 and for fixed point iteration, this changes to g(x) = ((x + 3 - x^4)/2)^(1/2).
This is my code snippet for the function in java:
'''
public static double function(double x) {
return Math.pow(((3 + x - Math.pow(x, 4))/2) , 1/2);
}
'''
My problem is that when I input an x value of 1.0 into the function, I get a value out of the function of 1.0, which is incorrect because the value should be 1.2247...
I need help with why this function is returning an incorrect value - or is there something that I'm doing which isn't right?
That 1/2 at the end will hurt you. You should consider using double parameters instead.
I'd suggest you changing 1/2 with 0.5, and even if you want to go safer instead of doing:
((3 + x - Math.pow(x, 4))/2
you could go with
((3 + x - Math.pow(x, 4))*0.5
It might be treating your double as an int and that's why you lose precision - can you try typecasting the hardcoded values as double?
Something like this:
public static double function(double x) {
double a = 3.0;
double b = 4.0;
double c = 0.5;
return Math.pow(((a + x - Math.pow(x, b))*c) , c);
}
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!
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I'm getting the error: illegal start of expression and don't know how to fix this. This is all declarations for a program I need to write with guidelines. The program is meant to calculate the cost of a boat. Thanks in advance!
import java.util.Scanner;
public class boat
{
public static void main(String[] args)
{
//declarations
....
double depreciationYear1 = bookValueBeginningYear1 * (2 * 100% / 3);
^
double bookValueBeginningYear2 = bookValueBeginningYear1 - depreciationYear1;
double depreciationYear2 = bookValueBeginningYear2 * (2 * 100% / 3);
^
double bookValueBeginningYear3 = bookValueBeginningYear2 - depreciationYear2;
double depreciationYear3 = bookValueBeginningYear3 * (2 * 100% / 3);
.... ^
double exciseTaxYear1 = 90% * boatPrice/1000 * 25;
^
double exciseTaxYear2 = 80% * boatPrice/1000 * 25;
^
double exciseTaxYear3 = 70% * boatPrice/1000 * 25;
.... ^
double insuranceYear1 = boatPrice * 1% + bookValueBeginningYear1* 3%;
^
double insuranceYear2 = boatPrice * 1% + bookValueBeginningYear2* 3%;
^
double insuranceYear3 = boatPrice * 1% + bookValueBeginningYear3* 3%;
.... ^
(2 * 100% / 3);
instead use:
(2 * 100 / 3); // Just remove the % from all the statement.
Because you are using two operator (%, /) at once.
This is the error into all the statement in the code, which you have marked.
The % is a modulus operator in java, which is used for calculating remainders of two number like 10%4 is 2. You might be getting confused by considering it as percentage.
In Java
% Modulus operator
Divides left hand operand by right hand operand and returns remainder
Example: B % A will give 0
/ Division operator
Divides left hand operand by right hand operand
Example: B / A will give 2
So in your case 2 * 100 % / 3
doesn't make any sense hence it is illegal
Have a quick look here to know the basic java operators
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);
In a program, I need to display the approximate PI value, which is close to 3.141592653.
The program is from The Art and Science of Java Chapter 6 Exercise 3.
Let me outline the exercise. Imagine there is a circle with radius r inscribed inside a square with length of 2r. If a dart is threw in a random fashion, the probability that the dart will fall in the circle is the ratio between the area of the circle and the square, which is PI*r^2/4*r^2, which is the same as PI/4. As a result, the more experiments, the more precise the the value of PI is. Now imagine we are doing it in a coordinates. Randomly choose 2 number, x and y each between -1 and 1. If x^2 + y^2 < 1, the coordinate point will fall into the circle with 1 radius centered in the middle of the coordinates.
Here is the program:
import acm.program.*;
import acm.util.*;
public class ApproxPIValue extends ConsoleProgram{
public void run() {
int total = 0; //calculating the time the dart falls into the circle.
for (int a = 0; a < 10000; a++) {
double x = rgen.nextDouble(-1.0, 1.0);
double y = rgen.nextDouble(-1.0, 1.0);
if ((Math.pow(x, 2) + Math.pow(y, 2)) < 1) {
total++;
}
}
println((double) (total / 10000)*4); // as I mentioned above, the result would be the approximate value of PI/4. By multiplying the result with 4, get the approximate PI value.//
}
/* set RandomGenerator as an instance variable. */
private RandomGenerator rgen = new RandomGenerator();
}
Another question is, is there anyway to print a String without extending any class. As you may notice in the code, I extends ConsoleProgram, which contains the println method. I know there is another method called System.out.print, but when I use it, it doesn't work, even Eclipse doesn't give any warning.
To the question in the title: a double has precision to 15 significant digits, irrespective of where the decimal point is.
In this code
(double) (total / 10000)*4)
you cast the resut of integer operations to a double. The result has 15 significant digits, but the number it represents is an integer. One way to correct is
(total / 10_000.0) * 4
(no need to convert to double explicitly).
Use System.out.println() to immediately see the result on-screen. The PrintStream referred to by System.out is a buffered stream which means it doesn't propagate each character to the screen as it is written. It will flush either when the buffer is full or at the sight of a newline character. This is why System.out.print() does not auto-flush.
Since total is an int, total/10000 uses integer division, i.e. it rounds to zero. You seem to try to use floating point division by casting to double, but the actual division happens before the cast is done. Change that line to
println(((double) total / 10000) *4);
to fix this.
BTW: Java's double has about 16 significant digits.
Re-reading your question, I suspect the problem is this line:
println((double) (total / 10000)*4);
You are dividing one integer with another, which will result in an integer. You then cast that to a double, but by then the damage is done.
To solve this, force the compiler to treat the 10000 value as a double. This will ensure the result is a double.
println((total / 10000d)*4);