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
Related
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;
}
}
}
So I need to calculate a value.
The input I get is this:
a is seed/m2. The value might a for example 56 but it might be 56.7 also.
b is in g's. for instance 600g
c is % value, might be 90.6 also
d is % value, might be 90.6 also
The result I get should be as kg/ha
Regular int does not cut it. The value of (56 * 600 / 100 / 100) / 100
will be 0.0336. I could multiply it with 10000 but I would lose the precision.
I also tried BigDecimal for this but it gave me a ArithmeticException: “Non-terminating decimal expansion; no exact representable decimal result” when I changed the values of my % variables to something else than 100.
What would be the best option to go with this? The calculation was easy to do in exel as it knew how to convert each value automatically, but doing it in Java code is another thing.
My solutions:
int version:
int a = Integer.decode(germinativeSeed.getText().toString());
int b = Integer.decode(seedMass.getText().toString());
int c = Integer.decode(clean.getText().toString());
int d = Integer.decode(germinative.getText().toString());
int result2 = ( a * b / c / d) / 100;
result is 0
BigDecimal solution:
BigDecimal result2;
BigDecimal a = new BigDecimal(germinativeSeed.getText().toString());
BigDecimal b = new BigDecimal(seedMass.getText().toString());
BigDecimal c;
BigDecimal d;
if (clean.getText().toString().equals("")) {
c = new BigDecimal("100");
} else {
c = new BigDecimal(clean.getText().toString());
}
if (germinative.getText().toString().equals("")) {
d = new BigDecimal("100");
} else {
d = new BigDecimal(germinative.getText().toString());
}
BigDecimal hundred = new BigDecimal("100");
BigDecimal test = new BigDecimal("10000");
result2 = a.multiply(b);
result2 = result2.divide(c, 2, RoundingMode.HALF_UP);
result2 = result2.divide(d, 2, RoundingMode.HALF_UP);
result2 = result2.divide(hundred, 2, RoundingMode.HALF_UP);
result2 = result2.multiply(test);
Result is correct with this only if % values are 100%.
double seed = (double) seedInput;
double m2 = (double) m2Input;
double b = (double) bInput; // unit 'g' is not relevant
double c = (double) cInput;
double d = (double) dInput;
double a = seed / m2;
int result2 = ( a * b / c / d) / 100.0;
So I converted everything to double so you won't have problems with implicit conversions to int.
Your problem comes when you have rational numbers like 1/3, this cannot be represented in a bigdecimal, as it has an infinite representation.
If you really need very big precision you should crate a new bigrational class, where you would store a nominator and denominator, and calculate with them. The code would be much mode complicated.
If you don't need that go for doubles.
Try using float or double (preferred double because of the precision).
Let suppose that I have double x. I would return nearest whole number of x. For example:
if x = 6.001 I would return 6
if x = 5.999 I would return 6
I suppose that I should use Math.ceil and Math.floor functions. But I don't know how return nearest whole number...
For your example, it seems that you want to use Math.rint(). It will return the closest integer value given a double.
int valueX = (int) Math.rint(x);
int valueY = (int) Math.rint(y);
public static void main(String[] args) {
double x = 6.001;
double y = 5.999;
System.out.println(Math.round(x)); //outputs 6
System.out.println(Math.round(y)); //outputs 6
}
The simplest method you get taught in most basic computer science classes is probably to add 0.5 (or subtract it, if your double is below 0) and simply cast it to int.
// for the simple case
double someDouble = 6.0001;
int someInt = (int) (someDouble + 0.5);
// negative case
double negativeDouble = -5.6;
int negativeInt = (int) (negativeDouble - 0.5);
// general case
double unknownDouble = (Math.random() - 0.5) * 10;
int unknownInt = (int) (unknownDouble + (unknownDouble < 0? -0.5 : 0.5));
int a = (int) Math.round(doubleVar);
This will round it and cast it to an int.
System.out.print(Math.round(totalCost));
Simple
Math.round() method in Java returns the closed int or long as per the argument
Math.round(0.48) = 0
Math.round(85.6) = 86
Similarly,
Math.ceil gives the smallest integer as per the argument.
Math.round(0.48) = 0
Math.round(85.6) = 85
Math.floor gives the largest integer as per the argument.
Math.round(0.48) = 1
Math.round(85.6) = 86
I have written a simple Java program as shown here:
public class Test {
public static void main(String[] args) {
int i1 =2;
int i2=5;
double d = 3 + i1/i2 +2;
System.out.println(d);
}
}
Since variable d is declared as double I am expecting the result of this program is 5.4 but I got the output as 5.0
Please help me in understanding this.
i1/i2 will be 0. Since i1 and i2 are both integers.
If you have int1/int2, if the answer is not a perfect integer, the digits after the decimal point will be removed. In your case, 2/5 is 0.4, so you'll get 0.
You can cast i1 or i2 to double (the other will be implicitly converted)
double d = 3 + (double)i1/i2 +2;
i1/i2 when converted to int gives 0. ie. why you are getting 5.0. Try this :
public static void main(String args[])
{
int i1 =2;
int i2=5;
double d = 3 + (double)i1/(double)i2 +2;
System.out.println(d);
}
This line is done in parts:
double d = 3 + i1/i2 +2;
double d = 3 + (i1/i2) +2;
double d = 3 + ((int)2/(int)3) +2;
double d = 3 + ((int)0) +2;
double d = (int)5;
double d = 5;
The double just means that the answer will be cast to a double, it doesn't have any effect till the answer is computed. You should write
double d = 3d + (double)i1/i2 +2d; //having one double in each "part" of the calculation will force it to use double maths, 3d and 2d are optional
i1/i2 will be 0 because both i1 and 12 are integers.
if you cast i1 or i2 to double then it will give the desired output.
double d = 3 + (double)i1/i2 +2;
This link provides information about data type conversion, both implicit and explicit type.
To provide exact answer to the question will be :
double d = 3 + (double)i1/i2 + 2
int i1 =2;
int i2=5;
double d = 3 + (double)i1/(double)i2 +2;
if i1/i2 will be fractional value then double will help it to be in fraction instead of int.
so now you will the result as you want. or you can also use following code
double d = 3+(double)i1/i2+2;
In this line i1 is converted into double which will be divided with i2 and result will be in double, so again result will be as 5.4
Since i1=2 and i2=5 are integer type and when you divide (2/5) them, It gives integer value (0) because fractional part(.4) get discarded.
So put (double)i1/i2 on the equation.