Can't get java to round 24.9999 properly, rounds to 8.? - java

I'm learning java and have a bit of code I am trying to write that should round 24.9999999 to 25. Instead, it goes to 8.
import java.io.*;
import java.util.*;
public class RadiusOfCircle
{
public static void main(String args[])
{
Scanner kbInput = new Scanner(System.in);
System.out.print("What is the area? _");
double area = kbInput.nextInt();
System.out.println("Radius of your circle is " + Math.sqrt( area / Math.PI));
double radius = Math.sqrt( area / Math.PI);
System.out.println("\nChecking your work now...\n area = pi*(r^2)\n " + area + " = 3.14 * (" + radius + ")^2");
double radiusSqrd = Math.pow(radius, 2);
System.out.println(" " + area + " = 3.14 * " + radiusSqrd);
System.out.println(" " + area + " = " + Math.PI * radiusSqrd);
System.out.println(area + " = " + (Math.round(radiusSqrd)));
System.out.println("Are the two values the same? \nIf yes, your code is correct! \nIf no, try again!");
}
}
Also, when it asks for keyboard input of what the area is, I put in 25.
This is the output:
What is the area? _25
Radius of your circle is 2.8209479177387813
Checking your work now...
area = pi*(r^2)
25.0 = 3.14 * (2.8209479177387813)^2
25.0 = 3.14 * 7.957747154594766
25.0 = 24.999999999999996
25.0 = 8
Are the two values the same?
If yes, your code is correct!
If no, try again!

You're rounding radiusSquared only, rather than Math.PI * radiusSquared. Fixing that should get the result you expect.

System.out.println(" " + area + " = " + Math.PI * radiusSqrd);
System.out.println(area + " = " + (Math.round(radiusSqrd)));
Shouldn't that be:
double value = Math.PI * radiusSqrd;
System.out.println(" " + area + " = " +value );
System.out.println(area + " = " + (Math.round(value )));

You omitted to multiply by PI:
System.out.println(area + " = " + Math.round(Math.PI * radiusSqrd));
Executing this gives the expected result.

float and double were designed for engineering problems, which have large positive powers of 10.. they cannot express negative powers of 10 accurately. In such cases use BigDecimal.
Run this simple code from Joshua Bloch's book Effective Java to get a sense of the extend of inaccuracy when dealing with negative powers and using double to store them. The answer should acutally be zero, but turns out to be something else entirely!
double funds = 1.00;
int itemsBought = 0;
for (double price = .10; funds >= price; price += .10) {
funds -= price;
itemsBought++;
}
System.out.println(itemsBought + ” items bought.”);
System.out.println(“Change: $” + funds);
}

If you want "accurate" math in Java, you should use the BigDecimal class, rather than either of the built-in floating point primitive types. double and float are always going to have issues like this, due to the nature of floating point arithmetic.
Please note that the recommended constructor for BigDecimal uses a String, not any of the numeric types. Since you are getting input from the console, this should be easy to implement.

You can use something like this:
double d = 10.938;
BigDecimal bd = new BigDecimal(d);
bd = bd.setScale(0,BigDecimal.ROUND_HALF_UP);
System.out.println(bd);
bd = new BigDecimal(d);
bd = bd.setScale(1,BigDecimal.ROUND_HALF_UP);
System.out.println(bd);
bd = new BigDecimal(d);
bd = bd.setScale(2,BigDecimal.ROUND_HALF_UP);
System.out.println(bd);
or like this:
double d = 10.938;
DecimalFormat decimalFormat = new DecimalFormat("#");
System.out.println(decimalFormat.format(d));
decimalFormat = new DecimalFormat("#.#");
System.out.println(decimalFormat.format(d));
decimalFormat = new DecimalFormat("#.##");
System.out.println(decimalFormat.format(d));

Related

Math formula not returning correct answer

So i'm trying to make a simple calculator to calculate a wilks score. I'm not getting the correct answer which i'm sure is because i'm not setting up the formula correctly. If I pass in a weight of 180, squat of 300, bench of 300, and deadlift of 400 in lbs I should be getting a wilks of 305.78 but i'm getting 2.0414858^-5
Heres my calcWilks method
public double calcWilks(double weight, double squat, double bench, double deadLift) {
double a = -216.0475144;
double b = 16.2606339;
double c = -0.002388645;
double d = -0.00113732;
double e = Math.pow(7.01863, -6);
double f = Math.pow(-1.291, -8);
double x = weight;
double coeff;
double score;
coeff = 500 / (a + (b*x) + (c* Math.pow(x, 2))+ (d* Math.pow(x, 3))
+ (e* Math.pow(x, 4)) + (f* Math.pow(x, 5)));
double total = squat + bench + deadLift;
score = coeff* total;
return score;
}
and heres a link to the actual formaula https://en.wikipedia.org/wiki/Wilks_Coefficient
I'm trying to use the Male formula
Thanks for any help!
The e coefficient's value in the wikipedia page is
7.01863E-06
but you've used
Math.pow(7.01863, -6)
That's not the same thing:
7.01863E-06 = 7.01863 * Math.pow(10, -6).
Just use the value 7.01863E-06 (or 7.01863e-6) directly.
(Same problem with f)
Also, note that the inputs to the formula should be in kilograms; not in pounds, as you state in the question.

Shape Calculator Pentagon and Hexagon Perimeter and Area

Sorry to trouble but it seems I'm a little lost.
I am currently creating a Shape Calculator for 2D and 3D shapes and I seem to be having a problem with the above mentioned shapes in the title.
Now I have gone about trying to use this particular section of code to get the Area of my Pentagon, I've seen this work elsewhere but can't figure out why it won't work here even after reviewing and comparing my code? I thought someone could possibly point out if this is the correct way to go about solving it or if I've made a mistake I can't see myself? Generally need a second opinion sorry.
double pen = scan.nextDouble();
double penPerm = pen * 5;
double A1 = pen * Math.sqrt(5);
double A2 = 5 + A1;
double A3 = Math.sqrt(5 * A2);
double PenA = (1.0 / 4.0) * A3 * Math.pow(pen, 2);
System.out.println("Your Perimitre is :" + penPerm + "cm and your Area is :" + PenA + "cm Squared");
The other problem I have how should I go about tackling the Hexagon but to be honest, the above Pentagon problem is my main concern before I move onto the Hexagon.
For a regular pentagon you can try the following code:
public static void main(String[] args) {
double side = 10;
double area = (1.0/4.0) * Math.sqrt(5*(5+2*Math.sqrt(5))) * Math.pow(side,2);
System.out.println("Your Perimitre is :" + 5*side + "cm and your Area is :" + area + "cm Squared");
}
You can also try the following code which takes no of sides (n) and edge size (s) as input and computes area for a regular polygon:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println(" Enter the number of sides in polygon");
int n = input.nextInt();
System.out.println(" Enter the distance between two points");
double s = input.nextDouble();
double area = (n * Math.pow(s, 2)) / (4 * Math.tan(Math.PI / n));
//Print result
System.out.println (" Area is " + area);
System.out.println (" Perimeter is " + s*n);
}

How to go about using tangents in Java?

I was bored and wanted to practice my java coding skills. I made a program that finds the area of a polygon based on what you know (radius, perimeter, apothem).
Here's a portion:
static void pentagon() {
System.out.println("Select what you know");
System.out.println("[1]Perimeter\n[2]Apothem\n[3]Radius");
info = input.nextInt();
if (info == 1) {
System.out.println("What is the perimeter of the pentagon?");
double per = input.nextDouble();
double apothem = per * .137638192;
double answer = apothem * per * .5;
System.out.println("The area of the pentagon is " + answer + " square units.");
} else if (info == 2) {
System.out.println("What is the apothem of the pentagon?");
double apothem = input.nextDouble();
double per = apothem / .137638192;
double answer = apothem * per * .5;
System.out.println("The area of the pentagon is " + answer + " square units.");
} else if (info == 3) {
System.out.println("What is the radius of the pentagon?");
double rad = input.nextDouble();
double per = rad / .1701301617;
double apothem = per * .137638192;
double answer = apothem * per * .5;
System.out.println("The area of the pentagon is " + answer + " square units.");
}
}
Due to the problem that all those decimals (ratio of apothem to perimeter) I had to figure out myself, I could only code a few useful ones.
If I knew how to use tangents, I could figure this out.
Ex: double apothem = length / tan(360/10/2)
(An apothem of a decagon)
Can someone show me how to code the previous line?
The recomended way would be to use java.lang.Math.tan(double a)
double apothem = 1 / java.lang.Math.tan( (2*java.lang.Math.PI)/(10*2))
unless there is some reason why you need extraordinary precision and this does not provide it. Then you may be able to find some third party alternative.
You're looking for the java.lang.Math class which has all the trig functions along with other useful constants like e and PI
So the apothem of a decagon where each side was length long and the equation = length/ 2 tan(180/ n) would be (after importing the Math class by putting at the top of your java file import java.lang.Math; )
EDIT
As user ajb points out, Math.tan() takes radians so you have to convert degrees to radians so you have to use toRadians() to convert from degrees to radians:
double apothem = length / (2 *Math.tan(Math.toRadians(180/10))

Java rounding the results of a division when it shouldn't be

So I have some code for scaling graphics to the size of a users screen by dividing the size of an 'Ideal' screen by the size of the users screen. Hers is a code snippet of what I'm doing:
public void setScaleFactor(GameContainer ui) {
scaleFactorWidth = 2880 / ui.getWidth();
scaleFactorHeight = 1800 / ui.getHeight();
System.out.println("Screen measured as: "
+ Integer.toString(ui.getWidth()) + "x"
+ Integer.toString(ui.getHeight()));
System.out.println("Scale factors are: "
+ Double.toString(scaleFactorWidth) + " "
+ Double.toString(scaleFactorHeight));
textScale = (scaleFactorWidth + scaleFactorHeight) / 2;
System.out.println("Text scale is: " + Double.toString(textScale));
}
Now if i run this on my computer (Mac Book pro with a screen resolution of 1440x900) the out come is that "scaleFactorWidth" is set to 2.0 and "scaleFactorHeight" is set to 2.0, this is as expected since my screen is exactly half the size of the target. But if run this code on a computer with a different resolution screen then the scaleFactors seem to get rounded up, I ran a test on a screen with 1024x600 and the "scaleFactorWidth" was set to 2.0 "scaleFactorHeight" was set to 3.0 when it should have been 2.8125 x 3.0.
IS this some sort of rounding error within java and if so how do I fix it?
Edit: Thanks for all the help, I've realised I was being very stupid as all I needed to do was add .0 to 2880 and 1800.
In these lines
scaleFactorWidth = 2880 / ui.getWidth();
scaleFactorHeight = 1800 / ui.getHeight();
The calculation itself is Integer-based (according to the later calls of Integer.toString()). Just the result is then casted to double.
Use this code instead, in order to have the actual computation use double values:
scaleFactorWidth = 2880.0 / ui.getWidth();
scaleFactorHeight = 1800.0 / ui.getHeight();
or
scaleFactorWidth = 2880.0 / (double)ui.getWidth();
scaleFactorHeight = 1800.0 / (double)ui.getHeight();
If you're talking about this GameContainer class, getWidth() and getHeight() return an int.
So you have to cast it as double
scaleFactorWidth = (double)2880 / ui.getWidth();
scaleFactorHeight = (double)1800 / ui.getHeight();
Cast it to Double.
scaleFactorWidth = (Double)2880 / ui.getWidth();
scaleFactorHeight = (Double)1800 / ui.getHeight();
ui.getWidth and ui.getHeight() returns you int and when you are performing operation on int it returns you int again. So convert your int value to Double.
Double scaleFactorWidth = new Double(2880) / new Double(ui.getWidth());
Double scaleFactorHeight = new Double(1800) / new Double(ui.getHeight());
Check below sample,
public static void main(String[] args) {
Double scaleFactorWidth = new Double(2880) / new Double(1024);
Double scaleFactorHeight = new Double(1024) / new Double(600);
System.out.println("Scale factors are: "
+ Double.toString(scaleFactorWidth) + " "
+ Double.toString(scaleFactorHeight));
Double textScale = (scaleFactorWidth + scaleFactorHeight) / 2;
System.out.println("Text scale is: " + Double.toString(textScale));
}
output:
Scale factors are: 2.8125 1.7066666666666668
Text scale is: 2.2595833333333335

how do i take a measurement like 5' 3"1/2 and then multiply it by 1.414 and display answer in same format on android java

what I'm doing is this, I leave the 5' alone then I turn 3" into a decimal of a foot by dividing by 12 then I divide the numerator by the denominator then I add it all up and multiply by 1.414 it works but I dont know how I would display the foot inches and fraction of a inch
c2c_fdecimal = f_num / f_den;
c2c_fdeci_fft = c2c_fdecimal / 12.0;
deci_of_foot = inchs / 12.0;
total_travel= feet + c2c_fdeci_fft + deci_of_foot;
toff_ftodeci = tkoff_numa / tkoff_dena;
tkoff_inch = tkoff_inch / 12.0;
sub_toff = toff_ftodeci / 12.0 + tkoff_inch;
ans = (total_travel * ffformula) - sub_toff;
//print out measurement format
ansint = (int)ans;
strip_inches = (int) ((ans - ansint) * 12.0);
//print answer
editText2.setText(ansint + " ft" + strip_inches + " in");
Here's how you'd figure out the feet and inches in Java:
double resultInInches; // you start with inches...
int feet = (int)(resultInInches / 12);
double rest = (resultInInches / 12) - feet;
int wholeInches = (int)rest;
rest = rest-wholeInches; // rest now holds the fraction of the inch, eg 0.4141
Now all that's left to do is display rest as a fraction. I'm not familiar with what is or is not permitted in the Android SDK, and there's a bunch of ways to do this (see this answer).

Categories