This question already has answers here:
Best method to round up to the nearest 0.05 in java
(4 answers)
Closed 8 years ago.
How is this possible in Java?
I have a float and I'd like to round it to the nearest .5.
For example:
1.1 should round to 1.0
1.3 should round to 1.5
2.5 should round to 2.5
3.223920 should round to 3.0
EDIT: Also, I don't just want the string representation, I want an actual float to work with after that.
#SamiKorhonen said this in a comment:
Multiply by two, round and finally divide by two
So this is that code:
public static double roundToHalf(double d) {
return Math.round(d * 2) / 2.0;
}
public static void main(String[] args) {
double d1 = roundToHalf(1.1);
double d2 = roundToHalf(1.3);
double d3 = roundToHalf(2.5);
double d4 = roundToHalf(3.223920);
double d5 = roundToHalf(3);
System.out.println(d1);
System.out.println(d2);
System.out.println(d3);
System.out.println(d4);
System.out.println(d5);
}
Output:
1.0
1.5
2.5
3.0
3.0
The general solution is
public static double roundToFraction(double x, long fraction) {
return (double) Math.round(x * fraction) / fraction;
}
In your case, you can do
double d = roundToFraction(x, 2);
to round to two decimal places
double d = roundToFraction(x, 100);
Although it is not that elegant, you could create your own Round function similarly to the following (it works for positive numbers, it needs some additions to support negatives):
public static double roundHalf(double number) {
double diff = number - (int)number;
if (diff < 0.25) return (int)number;
else if (diff < 0.75) return (int)number + 0.5;
else return (int)number + 1;
}
Related
This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 1 year ago.
I understand double as a variable type but in line 4 it might be used as datatype conversion. I just don't get the double used in line 6, am I completely missing the point here?
public static void main(String args[]) {
int discountPercentage = 10;
double totalPrice = 800;
double priceAfterDiscount = totalPrice * (1 - ((double) discountPercentage / 100));
if (totalPrice > 500) {
priceAfterDiscount = priceAfterDiscount * (1 - ((double) 5 / 100));
}
System.out.println("Customer has paid a bill of amount: "+ priceAfterDiscount);
}
Writing 5 / 100 is an int division as both operand are ints, and in Java that will result in 0.
See Int division: Why is the result of 1/3 == 0?
To get 0.05, you need to make a division with double
define an operand as double explicitly
5.0 / 100
5 / 100.0
cast an operand
(double) 5 / 100
5 / (double) 100
This question already has answers here:
Integer division: How do you produce a double?
(11 answers)
Closed 3 years ago.
I am trying to write a formula for one of my functions where I need to raise my X to power of Y. The values I am working with are really small and will get rounded up as soon as I use pow function of Math, BigInteger and BigDecimal.
For example if I use the following values it will return 1000 whereas it should return 1006.931669!
T0 = 1000, TN = 1, k = 1, N = 1000
double X = (finalTemp/initialTemp);
double A = Math.pow(X, (k/n));
double tk = initialTemp * A;
They are being divided in integer arithmetics. So dividing integer a by integer b you get how many times b fits into a, If the types of the operands are double, then "real" division is performed.
double X = (finalTemp/(double)initialTemp);
double A = Math.pow(X, (k/(double)n));
double tk = initialTemp * A;
the output is correct according to calculator
public class Main
{
public static void main(String[] args) {
double finalTemp = 1.0;
double initialTemp = 1000.0;
double k = 1.0;
double n = 1000.0;
double X = (finalTemp/initialTemp);
double A = Math.pow(X, (k/n));
double tk = initialTemp * A;
System.out.println(tk);
}
}
output is 993.1160484209338
This question already has answers here:
How do I format double input in Java WITHOUT rounding it?
(3 answers)
Closed 4 years ago.
if input = 31.6227890
then output = 31.6227
but the output is coming as 31.6228
You can use below function:
import java.text.DecimalFormat;
import java.math.RoundingMode;
public static double formatValue(Double number) {
DecimalFormat df = new DecimalFormat("####0.0000");
return Double.parseDouble(df.format(number));
}
Edit :
you have to add below code for rounding off.
df.setRoundingMode(RoundingMode.DOWN);
Input = 31.6227890
Output = 31.6227
If you want to round down, you can use truncation like this.
double d = 31.6227890;
d = ((long) (d * 10000)) / 10000.0; // truncates down to 0
System.out.println(d);
prints
31.6227
Note: this might print less than 4 digits. If you always want 4 you need to use formatting.
d = 31.60007890;
d = ((long) (d * 10000)) / 10000.0; // truncates down to 0
System.out.println(d);
System.out.printf("%.4f%n", d);
prints
31.6
31.6000
NOTE: For large values you wouldn't round them as this would result in an overflow.
private static final double WHOLE_NUMBER = 1L << 53;
public static double trunc4(double d) {
final double factor = 1e4;
return Math.abs(d) >= WHOLE_NUMBER / factor
? d
: ((long) (d * factor)) / factor;
}
The point at which you get an error is for numbers so large they are whole numbers anyway (due to the limits of the precision on double)
NOTE: If you used float the limit at which you would get a precision error is for much smaller values.
double d = 1024.00039999;
float f= (float) (long) (d * 10000) / 10000;
System.out.println(f);
prints
1024.0002
You can round down using a BigDecimal:
new BigDecimal(31.6227890d).setScale(4, RoundingMode.DOWN)
That returns the desired result: 31.6227.
For a double, you can use .doubleValue():
new BigDecimal(31.6227890d).setScale(4, RoundingMode.DOWN).doubleValue()
float i=(float)((int) (31.6227890 *10000))/10000;
System.out.println(i);
You can multiply it per 1000, use Math.floor() and divide it per 1000
double a = 10.345665654;
double b = Math.floor(a * 10000) / 10000;
System.out.println(b);
This question already has answers here:
Quickly square a double
(3 answers)
Closed 6 years ago.
I need help with this java exercise. The instructions are
Write a program that uses Math.sin() and Math.cos() to check that the
value of sin2θ + cos2θ is approximately 1 for any θ entered as a
command-line argument. Just print the value. Why are the values not
always exactly 1?
My code so far (It is my first code so please no harsh judgement).
public class math {
public static void main(String[] args) {
//Changes the data types from string to double
double a = Double.parseDouble(args[0]);
double b = Double.parseDouble(args[1]);
//Does the calculation math functions
double s = 2*Math.sin(a);
double c = 2*Math.cos(b);
double target = .9998; // var for comparing if less than 1
double answer = s + c;
// Prints the answer and checks whether its less than 1
System.out.println(answer < target);
System.out.println(answer);
}
}
I guessed on squaring the sin and cos. If anyone has quick suggestion on how to square sin and cos and if there is an error in my little program I will appreciate your help.
I think what you are going to do is this. You got this wrong meaning of "sin^2θ". It's actual meaning is sin2θ. And same for cos. This is the code you are looking for.
double a = Double.parseDouble(args[0]);
//Does the calculation math functions
double s = Math.pow(Math.sin(a),2);
double c = Math.pow(Math.cos(b),2);
double target = .9998; // var for comparing if less than 1
double answer = s + c;
// Prints the answer and checks whether its less than 1
System.out.println(answer < target);
System.out.println(answer);
you have one theta so: you need just args[0] and not args[1].
so a=b in your sample code.
squaring the sin and cos and adding:
Option 1:
double stheta = Math.sin(theta);
double ctheta = Math.cos(theta);
double answer = stheta*stheta + ctheta*ctheta;
Option 2:
double s2 = Math.pow(Math.sin(theta),2);
double c2 = Math.pow(Math.cos(theta),2);
double answer = s2 + c2;
working sample code:
package javaapplication1;
public class JavaApplication1 {
public static void main(String[] args) {
double theta = Double.parseDouble(args[0]);
double stheta = Math.sin(theta);
double ctheta = Math.cos(theta);
double answer = stheta*stheta + ctheta*ctheta;
System.out.println(answer);
}
}
and see:
Java - does double and float percision depend on the machine?
Test Number For Maximum Precision In Java
Floating point numbers are not exact representations. Double precision 64 bit IEEE floating point representation only gives 17-18 digits, so you always compare differences to a tolerance.
I would recommend multiplying a number by itself for squaring over using Math.pow().
Here's a JUnit test that shows how I'd do it:
package math;
import org.junit.Test;
import org.junit.Assert;
/**
* Created by Michael
* Creation date 6/25/2016.
* #link https://stackoverflow.com/questions/38024899/how-do-i-square-sin-and-cos-in-java
*/
public class MathTest {
public static final double TOLERANCE = 1.0e-8;
#Test
public void testUnitCircleIdentity() {
int n = 10;
double t = 0.0;
for (int i = 0; i < n; ++i) {
double s = Math.sin(t);
double c = Math.cos(t);
double actual = s*s + c*c;
Assert.assertEquals(1.0, actual, TOLERANCE);
t += Math.PI/n;
}
}
}
I am doing a school assignment in which I solve an equation involving coordinates in a circle (r^2 = x^2 + y^2) were r = 1, and you increment through x values solving for y. I am getting a repeating decimals even though I only incrementing in tenths. I have no idea why and have tried it in a few different ways. Here is the code.
double r = 1;
double rSqr;
double x = 1;
double xSqr;
double y;
double ySqr;
double inc = 0.1;
int count = 0;
while(x > -r)
{
x = r - (count * inc);
rSqr = Math.pow(r, 2);
xSqr = Math.pow(x, 2);
ySqr = rSqr - xSqr;
y = Math.sqrt(ySqr);
count++;
System.out.println(x + " " + y);
}
and the output is this
1.0 0.0
0.9 0.4358898943540673
0.8 0.5999999999999999
0.7 0.714142842854285
0.6 0.8
0.5 0.8660254037844386
0.3999999999999999 0.9165151389911681
0.29999999999999993 0.9539392014169457
0.19999999999999996 0.9797958971132712
0.09999999999999998 0.99498743710662
0.0 1.0
-0.10000000000000009 0.99498743710662
-0.20000000000000018 0.9797958971132712
-0.30000000000000004 0.9539392014169457
-0.40000000000000013 0.9165151389911679
-0.5 0.8660254037844386
-0.6000000000000001 0.7999999999999999
-0.7000000000000002 0.7141428428542849
-0.8 0.5999999999999999
-0.9000000000000001 0.43588989435406705
-1.0 0.0
The problem is that double is imprecise. It uses 64 bits to represent decimal numbers; some bits are used for the numeric part, and some for the exponent, but many seemingly simple decimal numbers can not be accurately represented in this way, for example 0.1. See this wiki article for more.
One way around the problem is to display the number using DecimalFormat, which can round the number for presentation purposes. Here's some example code:
public static void main(String[] args) {
DecimalFormat decimalFormat = new DecimalFormat("#0.000");
double d = 1 - .9; // one way to get a repeating decimal floating point number
System.out.println(d);
System.out.println(decimalFormat.format(d));
}
Output:
0.09999999999999998
0.100
It is the IEEE 754 floating point representation.
Use BigDecimal as datatype instead of double to solve your problem.
But take care as BigDecimal is immutable.
BigDecimal r = BigDecimal.ONE;
BigDecimal rSqr;
BigDecimal x = BigDecimal.ONE;
BigDecimal xSqr;
BigDecimal y;
BigDecimal ySqr;
BigDecimal inc = new BigDecimal("0.1");
int count = 0;
while(x.compareTo(r.negate())>0)
{
// i'll let you fill in this part
}