Math.ceil not rounding the value - java

double totalInches = d * 0.3937;
double feetPart = totalInches / 12;
int inchesPart = (int) Math.ceil(totalInches - (feetPart * 12));
return (feetPart) + "' " + inchesPart + "''";
I am getting a value 6.9999999 ' 0". I am returning a string, is it the reason why the decimals values in feet is not getting rounded off.
I tried without casting too. double inchesPart = Math.ceil(totalInches - (feetPart * 12));, but still i get the same result.

Surely you need:
int feetPart = (int)Math.floor(totalInches / 12);
or just:
int feetPart = (int)(totalInches / 12);

To get the two parts you can use
int totalInches = (int) (d * 0.3937);
int feetPart = totalInches / 12;
int feetInchPart = totalInches % 12;

Related

my math is broken on TextView

To be honest I've just started with programming but for the life of me I can't figure out where I'm wrong.
the math is:
10$ / 2 hours
tips per hour = 5 (i get 0.2)
waiter 1 pay = 10 (i get 0.4?)
screenshot
The Calculation in MainActivity:
double resultTotalHours = cWaiter1Hours + cWaiter2Hours + cWaiter3Hours + cWaiter4Hours;
double calcTipsPerHour = resultTotalHours / totalTips;
double resultBarsCut = (totalTips * (cBarCutInput / 100));
double resultTaxDeposit = resultTotalHours * 3;
double resultTipsPerHour = (totalTips - resultBarsCut - resultTaxDeposit) / resultTotalHours;
double resultWaiter1Pay = cWaiter1Hours * resultTipsPerHour;
double resultWaiter2Pay = cWaiter2Hours * resultTipsPerHour;
double resultWaiter3Pay = cWaiter3Hours * resultTipsPerHour;
double resultWaiter4Pay = cWaiter4Hours * resultTipsPerHour;
double resultWaiter1NoTax = cWaiter1Hours * calcTipsPerHour;
double resultWaiter2NoTax = cWaiter2Hours * calcTipsPerHour;
double resultWaiter3NoTax = cWaiter3Hours * calcTipsPerHour;
double resultWaiter4NoTax = cWaiter4Hours * calcTipsPerHour;
Casting the results to the TextViews:
if (calcTipsPerHour <= 30) {
totalHoursView.setText(Double.toString(resultTotalHours));
tipsPerHourView.setText(Double.toString(calcTipsPerHour));
barsCutView.setText(Double.toString(0));
taxDepositView.setText(Double.toString(0));
waiter1Pay.setText(Double.toString(resultWaiter1NoTax));
waiter2Pay.setText(Double.toString(resultWaiter2NoTax));
waiter3Pay.setText(Double.toString(resultWaiter3NoTax));
waiter4Pay.setText(Double.toString(resultWaiter4NoTax));
} else {
totalHoursView.setText(Double.toString(resultTotalHours));
tipsPerHourView.setText(Double.toString(resultTipsPerHour));
barsCutView.setText(Double.toString(resultBarsCut));
taxDepositView.setText(Double.toString(resultTaxDeposit));
waiter1Pay.setText(Double.toString(resultWaiter1Pay));
waiter2Pay.setText(Double.toString(resultWaiter2Pay));
waiter3Pay.setText(Double.toString(resultWaiter3Pay));
waiter4Pay.setText(Double.toString(resultWaiter4Pay));
}
The problem is here:
double calcTipsPerHour = resultTotalHours / totalTips;
This is currently doing 2 / 10 = 0.2.
You want to do the reciprocal:
double calcTipsPerHour = totalTips / resultTotalHours;
This should also fix your waiter's pay
You put hours in the numerator and tips in the denominator so you are getting the inverse of what you want: hours/tip
What you want is:
double calcTipsPerHour = totalTips / resultTotalHours;

How to calculate the angle between two vectors?

We are trying to get the cos value between v and u but we are getting results much higher than 1 or lesser than 0
Where :
vx = in.nextInt(); // x speed of your pod
vy = in.nextInt(); // y speed of your pod
int ux = nextCheckPointIdX - x;
int uy = nextCheckPointIdY - y;
Here is the formula :
double cos = (vx*ux + vy*uy) / ( Math.sqrt(Math.pow(vx, 2) + Math.pow(vy, 2)) + Math.sqrt(Math.pow(ux, 2) + Math.pow(uy, 2)) );
Do you find any errors in the previous line ?
The denominator was having the problem.
int num = (vx*ux + vy*uy);
double den = (Math.sqrt(Math.pow(vx, 2) + Math.pow(vy, 2)) * (Math.sqrt(Math.pow(ux, 2) + Math.pow(uy, 2))) );
double cos = num / den;
System.out.println(cos);
System.out.println(Math.acos(cos));

Updating my variables in a for loop?

I'm trying to update my variable startPreyPopulationSize and startPredatorPopulation size everytime it iterates but I'm not sure how to go about that since the bottom for loop affects the top one right?
//Equation to find out prey population size.
for(double rate = 0; rate <= numberOfPeriods; rate++) {
double partOne = startPreyPopulationSize / rate * (1 + RATE_A_BIRTH - RATE_B_PREDATION * (startPredatorPopulationSize / rate));
double updatedPreyPopulation = startPreyPopulationSize / (rate + 1);
updatedPreyPopulation = partOne;
System.out.printf("Period %5.0f: Prey Population %.2f; \n", rate, updatedPreyPopulation);
}
//Equation to find out predator population size.
for(double rate2 = 0; rate2 <= numberOfPeriods; rate2++) {
double partTwoEquation = startPredatorPopulationSize / rate2 * (1 - RATE_C_DEATHS + RATE_D_INCREASE * (startPreyPopulationSize / rate2));
double updatedPredatorPopulation = startPredatorPopulationSize / (rate2 + 1);
updatedPredatorPopulation = partTwoEquation;
System.out.printf("Period %5.0f: Predator Population %.2f; \n", rate2, updatedPredatorPopulation);
}
UPDATED CODE I'm basing my formula off of this if it helps http://i.imgur.com/rUQ774q.jpg I know my formula is off somehow.
//Equation to find out prey population size.
for(double rate = 0; rate < numberOfPeriods; rate++) {
partOne = startPreyPopulationSize / rate * (1 + RATE_A_BIRTH - RATE_B_PREDATION * (startPredatorPopulationSize / rate));
currentPreyPopulationSize = startPreyPopulationSize / (rate + 1);
currentPreyPopulationSize = partOne;
System.out.printf("Period %5.0f: Prey Population %.2f; \n", rate, currentPreyPopulationSize);
partTwoEquation = startPredatorPopulationSize / rate * (1 - RATE_C_DEATHS + RATE_D_INCREASE * (startPreyPopulationSize / rate));
currentPredatorPopulationSize = startPredatorPopulationSize / (rate + 1);
currentPredatorPopulationSize = partTwoEquation;
System.out.printf("Period %5.0f: Predator Population %.2f; \n", rate, currentPredatorPopulationSize);
startPreyPopulationSize = currentPreyPopulationSize;
startPredatorPopulationSize = currentPredatorPopulationSize;
}
Well your code for equations you provided is wrong.
1) In equation you have no division by rate, so it should look like
double currentPreyPopulationSize = startPreyPopulationSize * (1 + RATE_A_BIRTH - RATE_B_PREDATION * (startPredatorPopulationSize));
2) Also this division causing the -Infinity, because rate is 0 for the first iteration.

Image over another already drawn image in CAPTCHA

I want to generate a captcha by myself without using any other API, but here are some issues. In my code I have treated each character as an image and then form some operation on them but now I want to rotate whole image with respect to its midpoint.
Here is my sample code:
for (int i = 0; i < charsToPrint; i++)
{
double randomValue =Math.random();
int randomIndex = (int) Math.round(randomValue * (chars.length - 1));
char characterToShow = chars[randomIndex];
finalString.append(characterToShow);
int charWidth = fontMetrics.charWidth(characterToShow);
int charDim = Math.max(maxAdvance, fontHeight);
//int halfCharDim = (int) (charDim / 2);
charImage = new BufferedImage(charDim, charDim,BufferedImage.TYPE_INT_ARGB);
charGraphics = charImage.createGraphics();
charGraphics.setColor(textColor);
charGraphics.setFont(textFont);
int rn = ran.nextInt((20 - 10) + 1) + 10;
x1=charDim/rn;
int rn1 = ran.nextInt((20 - 10) + 1) + 10;
y1=charDim/rn1;
int charX = (int) ((0.5 * charDim - 0.5 * charWidth)+x1);
int charY=(int) ((charDim - fontMetrics.getAscent()) / 2 + fontMetrics.getAscent()+y1);
charGraphics.drawString("" + characterToShow, charX, charY);
float x = horizMargin + spacePerChar * (i) - charDim / 2.0f;
int y = (int) ((height - charDim) / 2);
g.setColor(Color.GREEN);
g.drawImage(charImage, (int) (x+x1), (int)(y+y1), charDim,charDim, null,null);
charGraphics.dispose();
}

Strange issue in converting Feet and Inches to Centimeter and Vice Versa

public static double convertFeetandInchesToCentimeter(String feet, String inches) {
double heightInFeet = 0;
double heightInInches = 0;
try {
if (feet != null && feet.trim().length() != 0) {
heightInFeet = Double.parseDouble(feet);
}
if (inches != null && inches.trim().length() != 0) {
heightInInches = Double.parseDouble(inches);
}
} catch (NumberFormatException nfe) {
}
return (heightInFeet * 30.48) + (heightInInches * 2.54);
}
Above is the function for converting Feet and Inches to Centimeter.Below is the function for converting Centimeter back to Feet and Inches.
public static String convertCentimeterToHeight(double d) {
int feetPart = 0;
int inchesPart = 0;
if (String.valueOf(d) != null && String.valueOf(d).trim().length() != 0) {
feetPart = (int) Math.floor((d / 2.54) / 12);
inchesPart = (int) Math.ceil((d / 2.54) - (feetPart * 12));
}
return String.format("%d' %d''", feetPart, inchesPart);
}
I have a problem when i enter normal values like 5 Feet and 6 Inches, its converting perfectly to centimeter and again it gets converted back to 5 Feet and 6 Inches.
The Problem is when i convert 1 Feet and 1 inches or 2 Feet and 2
inches, its getting converted back to 1 Feet 2 inches and 2 Feet 3
inches.
I ran the following code
public class FeetInches{
public static void main(String[] args){
double d = convertFeetandInchesToCentimeter("1","1");
String back_again = convertCentimeterToHeight(d);
System.out.println(back_again);
}
public static double convertFeetandInchesToCentimeter(String feet, String inches) {
double heightInFeet = 0;
double heightInInches = 0;
try {
if (feet != null && feet.trim().length() != 0) {
heightInFeet = Double.parseDouble(feet);
}
if (inches != null && inches.trim().length() != 0) {
heightInInches = Double.parseDouble(inches);
}
} catch (NumberFormatException nfe) {
}
return (heightInFeet * 30.48) + (heightInInches * 2.54);
}
public static String convertCentimeterToHeight(double d) {
int feetPart = 0;
int inchesPart = 0;
if (String.valueOf(d) != null && String.valueOf(d).trim().length() != 0) {
feetPart = (int) Math.floor((d / 2.54) / 12);
System.out.println((d / 2.54) - (feetPart * 12));
inchesPart = (int) Math.ceil((d / 2.54) - (feetPart * 12));
}
return String.format("%d' %d''", feetPart, inchesPart);
}
}
And got
1.0000000000000018
1' 2''
By using the ceiling function you are rounding up to 2 when you really want to be rounding down to 1.
I believe:
inchesPart = (int) Math.ceil((d / 2.54) - (feetPart * 12));
Should be:
inchesPart = (int) Math.floor((d / 2.54) - (feetPart * 12));
The problem is because of the way java handles floating point numbers.
inchesPart = (int) Math.ceil(Math.round((d / 2.54) - (feetPart * 12)));
or
inchesPart = (int) Math.floor((d / 2.54) - (feetPart * 12));
In case of input 2,2 the original value of inchesPart is 2.0000000000000036 -> ceil ->3
The main issue with you're code is that you're not using the same rounding function for each part :
int feetPart = (int) Math.floor((d / 2.54) / 12);
^^^^^
int inchesPart = (int) Math.ceil((d / 2.54) - (feetPart * 12));
^^^^
You should also do the rounding before the decomposition in order to obtain consistent results :
int feetPart = ((int) Math.round(d / 2.54)) / 12;
int inchesPart = ((int) Math.round((d / 2.54)) - (feetPart * 12);
Which could be factorized to:
int inches = (int) Math.round(d / 2.54);
int feetPart = inches / 12;
int inchesPart = inches - (feetPart * 12);
Or since ( inches - ( ( inches / 12 ) * 12) ) == ( inches % 12 ):
int inches = (int) Math.round(d / 2.54);
feetPart = inches / 12;
inchesPart = inches % 12;
You can interchange Math.round with Math.floor or Math.ceil depending on the result you expect.
I know this is old may be useful for someone else (Kotlin version)
fun feetToCentimeter(feetval: String): String {
var heightInFeet = 0.0
var heightInInches = 0.0
var feet = ""
var inches = ""
if (!TextUtils.isEmpty(feetval)) {
if (feetval.contains("'")) {
feet = feetval.substring(0, feetval.indexOf("'"))
}
if (feetval.contains("\"")) {
inches = feetval.substring(feetval.indexOf("'") + 1, feetval.indexOf("\""))
}
}
try {
if (feet.trim { it <= ' ' }.isNotEmpty()) {
heightInFeet = feet.toDouble()
}
if (inches.trim { it <= ' ' }.isNotEmpty()) {
heightInInches = inches.toDouble()
}
} catch (nfe: NumberFormatException) {
}
return (((heightInFeet * 12.0) + heightInInches) * 2.54).toString()
}
fun centimeterToFeet(centemeter: String?): String {
var feetPart = 0
var inchesPart = 0
if (!TextUtils.isEmpty(centemeter)) {
val dCentimeter = java.lang.Double.valueOf(centemeter!!)
feetPart = Math.floor((dCentimeter / 2.54) / 12).toInt()
println(dCentimeter / 2.54 - feetPart * 12)
inchesPart = Math.floor((dCentimeter / 2.54) - (feetPart * 12)).toInt()
}
return String.format("%d' %d\"", feetPart, inchesPart)
}

Categories