Beginners Java Question (int, float) - java

int cinema,dvd,pc,total;
double fractionCinema, fractionOther;
fractionCinema=(cinema/total)*100; //percent cinema
So when I run code to display fractionCinema, it just gives me zeros. If I change all the ints to doubles, then it gives me what Im looking for. However, I use cinema, pc, and total elsewhere and they have to be displayed as ints, not decimals. What do I do?

When you divide two ints (eg, 2 / 3), Java performs an integer division, and truncates the decimal portion.
Therefore, 2 / 3 == 0.
You need to force Java to perform a double division by casting either operand to a double.
For example:
fractionCinema = (cinema / (double)total) * 100;

Try this instead:
int cinema, total;
int fractionCinema;
fractionCinema = cinema*100 / total; //percent cinema
For example, if cinema/(double)total is 0.5, then fractionCinema would be 50. And no floating-point operations are required; all of the math is done using integer arithmetic.
Addendum
As pointed out by #user949300, the code above rounds down to the nearest integer. To round the result "properly", use this:
fractionCinema = (cinema*100 + 50) / total; //percent cinema

When you divide two ints, Java will do integer division, and the fractional part will be truncated.
You can either explicitly cast one of the arguments to a double via cinema/(double) total or implicitly using an operation such as cinema*1.0/total

As some people have already stated, Java will automatically cut off any fractional parts when doing division of integers. Just change the variables from int to double.

Related

Java - Numbers aren't subtracting correctly? [duplicate]

public class doublePrecision {
public static void main(String[] args) {
double total = 0;
total += 5.6;
total += 5.8;
System.out.println(total);
}
}
The above code prints:
11.399999999999
How would I get this to just print (or be able to use it as) 11.4?
As others have mentioned, you'll probably want to use the BigDecimal class, if you want to have an exact representation of 11.4.
Now, a little explanation into why this is happening:
The float and double primitive types in Java are floating point numbers, where the number is stored as a binary representation of a fraction and a exponent.
More specifically, a double-precision floating point value such as the double type is a 64-bit value, where:
1 bit denotes the sign (positive or negative).
11 bits for the exponent.
52 bits for the significant digits (the fractional part as a binary).
These parts are combined to produce a double representation of a value.
(Source: Wikipedia: Double precision)
For a detailed description of how floating point values are handled in Java, see the Section 4.2.3: Floating-Point Types, Formats, and Values of the Java Language Specification.
The byte, char, int, long types are fixed-point numbers, which are exact representions of numbers. Unlike fixed point numbers, floating point numbers will some times (safe to assume "most of the time") not be able to return an exact representation of a number. This is the reason why you end up with 11.399999999999 as the result of 5.6 + 5.8.
When requiring a value that is exact, such as 1.5 or 150.1005, you'll want to use one of the fixed-point types, which will be able to represent the number exactly.
As has been mentioned several times already, Java has a BigDecimal class which will handle very large numbers and very small numbers.
From the Java API Reference for the BigDecimal class:
Immutable,
arbitrary-precision signed decimal
numbers. A BigDecimal consists of an
arbitrary precision integer unscaled
value and a 32-bit integer scale. If
zero or positive, the scale is the
number of digits to the right of the
decimal point. If negative, the
unscaled value of the number is
multiplied by ten to the power of the
negation of the scale. The value of
the number represented by the
BigDecimal is therefore (unscaledValue
× 10^-scale).
There has been many questions on Stack Overflow relating to the matter of floating point numbers and its precision. Here is a list of related questions that may be of interest:
Why do I see a double variable initialized to some value like 21.4 as 21.399999618530273?
How to print really big numbers in C++
How is floating point stored? When does it matter?
Use Float or Decimal for Accounting Application Dollar Amount?
If you really want to get down to the nitty gritty details of floating point numbers, take a look at What Every Computer Scientist Should Know About Floating-Point Arithmetic.
When you input a double number, for example, 33.33333333333333, the value you get is actually the closest representable double-precision value, which is exactly:
33.3333333333333285963817615993320941925048828125
Dividing that by 100 gives:
0.333333333333333285963817615993320941925048828125
which also isn't representable as a double-precision number, so again it is rounded to the nearest representable value, which is exactly:
0.3333333333333332593184650249895639717578887939453125
When you print this value out, it gets rounded yet again to 17 decimal digits, giving:
0.33333333333333326
If you just want to process values as fractions, you can create a Fraction class which holds a numerator and denominator field.
Write methods for add, subtract, multiply and divide as well as a toDouble method. This way you can avoid floats during calculations.
EDIT: Quick implementation,
public class Fraction {
private int numerator;
private int denominator;
public Fraction(int n, int d){
numerator = n;
denominator = d;
}
public double toDouble(){
return ((double)numerator)/((double)denominator);
}
public static Fraction add(Fraction a, Fraction b){
if(a.denominator != b.denominator){
double aTop = b.denominator * a.numerator;
double bTop = a.denominator * b.numerator;
return new Fraction(aTop + bTop, a.denominator * b.denominator);
}
else{
return new Fraction(a.numerator + b.numerator, a.denominator);
}
}
public static Fraction divide(Fraction a, Fraction b){
return new Fraction(a.numerator * b.denominator, a.denominator * b.numerator);
}
public static Fraction multiply(Fraction a, Fraction b){
return new Fraction(a.numerator * b.numerator, a.denominator * b.denominator);
}
public static Fraction subtract(Fraction a, Fraction b){
if(a.denominator != b.denominator){
double aTop = b.denominator * a.numerator;
double bTop = a.denominator * b.numerator;
return new Fraction(aTop-bTop, a.denominator*b.denominator);
}
else{
return new Fraction(a.numerator - b.numerator, a.denominator);
}
}
}
Observe that you'd have the same problem if you used limited-precision decimal arithmetic, and wanted to deal with 1/3: 0.333333333 * 3 is 0.999999999, not 1.00000000.
Unfortunately, 5.6, 5.8 and 11.4 just aren't round numbers in binary, because they involve fifths. So the float representation of them isn't exact, just as 0.3333 isn't exactly 1/3.
If all the numbers you use are non-recurring decimals, and you want exact results, use BigDecimal. Or as others have said, if your values are like money in the sense that they're all a multiple of 0.01, or 0.001, or something, then multiply everything by a fixed power of 10 and use int or long (addition and subtraction are trivial: watch out for multiplication).
However, if you are happy with binary for the calculation, but you just want to print things out in a slightly friendlier format, try java.util.Formatter or String.format. In the format string specify a precision less than the full precision of a double. To 10 significant figures, say, 11.399999999999 is 11.4, so the result will be almost as accurate and more human-readable in cases where the binary result is very close to a value requiring only a few decimal places.
The precision to specify depends a bit on how much maths you've done with your numbers - in general the more you do, the more error will accumulate, but some algorithms accumulate it much faster than others (they're called "unstable" as opposed to "stable" with respect to rounding errors). If all you're doing is adding a few values, then I'd guess that dropping just one decimal place of precision will sort things out. Experiment.
You may want to look into using java's java.math.BigDecimal class if you really need precision math. Here is a good article from Oracle/Sun on the case for BigDecimal. While you can never represent 1/3 as someone mentioned, you can have the power to decide exactly how precise you want the result to be. setScale() is your friend.. :)
Ok, because I have way too much time on my hands at the moment here is a code example that relates to your question:
import java.math.BigDecimal;
/**
* Created by a wonderful programmer known as:
* Vincent Stoessel
* xaymaca#gmail.com
* on Mar 17, 2010 at 11:05:16 PM
*/
public class BigUp {
public static void main(String[] args) {
BigDecimal first, second, result ;
first = new BigDecimal("33.33333333333333") ;
second = new BigDecimal("100") ;
result = first.divide(second);
System.out.println("result is " + result);
//will print : result is 0.3333333333333333
}
}
and to plug my new favorite language, Groovy, here is a neater example of the same thing:
import java.math.BigDecimal
def first = new BigDecimal("33.33333333333333")
def second = new BigDecimal("100")
println "result is " + first/second // will print: result is 0.33333333333333
Pretty sure you could've made that into a three line example. :)
If you want exact precision, use BigDecimal. Otherwise, you can use ints multiplied by 10 ^ whatever precision you want.
As others have noted, not all decimal values can be represented as binary since decimal is based on powers of 10 and binary is based on powers of two.
If precision matters, use BigDecimal, but if you just want friendly output:
System.out.printf("%.2f\n", total);
Will give you:
11.40
You're running up against the precision limitation of type double.
Java.Math has some arbitrary-precision arithmetic facilities.
You can't, because 7.3 doesn't have a finite representation in binary. The closest you can get is 2054767329987789/2**48 = 7.3+1/1407374883553280.
Take a look at http://docs.python.org/tutorial/floatingpoint.html for a further explanation. (It's on the Python website, but Java and C++ have the same "problem".)
The solution depends on what exactly your problem is:
If it's that you just don't like seeing all those noise digits, then fix your string formatting. Don't display more than 15 significant digits (or 7 for float).
If it's that the inexactness of your numbers is breaking things like "if" statements, then you should write if (abs(x - 7.3) < TOLERANCE) instead of if (x == 7.3).
If you're working with money, then what you probably really want is decimal fixed point. Store an integer number of cents or whatever the smallest unit of your currency is.
(VERY UNLIKELY) If you need more than 53 significant bits (15-16 significant digits) of precision, then use a high-precision floating-point type, like BigDecimal.
private void getRound() {
// this is very simple and interesting
double a = 5, b = 3, c;
c = a / b;
System.out.println(" round val is " + c);
// round val is : 1.6666666666666667
// if you want to only two precision point with double we
// can use formate option in String
// which takes 2 parameters one is formte specifier which
// shows dicimal places another double value
String s = String.format("%.2f", c);
double val = Double.parseDouble(s);
System.out.println(" val is :" + val);
// now out put will be : val is :1.67
}
Use java.math.BigDecimal
Doubles are binary fractions internally, so they sometimes cannot represent decimal fractions to the exact decimal.
/*
0.8 1.2
0.7 1.3
0.7000000000000002 2.3
0.7999999999999998 4.2
*/
double adjust = fToInt + 1.0 - orgV;
// The following two lines works for me.
String s = String.format("%.2f", adjust);
double val = Double.parseDouble(s);
System.out.println(val); // output: 0.8, 0.7, 0.7, 0.8
Doubles are approximations of the decimal numbers in your Java source. You're seeing the consequence of the mismatch between the double (which is a binary-coded value) and your source (which is decimal-coded).
Java's producing the closest binary approximation. You can use the java.text.DecimalFormat to display a better-looking decimal value.
Short answer: Always use BigDecimal and make sure you are using the constructor with String argument, not the double one.
Back to your example, the following code will print 11.4, as you wish.
public class doublePrecision {
public static void main(String[] args) {
BigDecimal total = new BigDecimal("0");
total = total.add(new BigDecimal("5.6"));
total = total.add(new BigDecimal("5.8"));
System.out.println(total);
}
}
Multiply everything by 100 and store it in a long as cents.
Computers store numbers in binary and can't actually represent numbers such as 33.333333333 or 100.0 exactly. This is one of the tricky things about using doubles. You will have to just round the answer before showing it to a user. Luckily in most applications, you don't need that many decimal places anyhow.
Floating point numbers differ from real numbers in that for any given floating point number there is a next higher floating point number. Same as integers. There's no integer between 1 and 2.
There's no way to represent 1/3 as a float. There's a float below it and there's a float above it, and there's a certain distance between them. And 1/3 is in that space.
Apfloat for Java claims to work with arbitrary precision floating point numbers, but I've never used it. Probably worth a look.
http://www.apfloat.org/apfloat_java/
A similar question was asked here before
Java floating point high precision library
Use a BigDecimal. It even lets you specify rounding rules (like ROUND_HALF_EVEN, which will minimize statistical error by rounding to the even neighbor if both are the same distance; i.e. both 1.5 and 2.5 round to 2).
Why not use the round() method from Math class?
// The number of 0s determines how many digits you want after the floating point
// (here one digit)
total = (double)Math.round(total * 10) / 10;
System.out.println(total); // prints 11.4
Check out BigDecimal, it handles problems dealing with floating point arithmetic like that.
The new call would look like this:
term[number].coefficient.add(co);
Use setScale() to set the number of decimal place precision to be used.
If you have no choice other than using double values, can use the below code.
public static double sumDouble(double value1, double value2) {
double sum = 0.0;
String value1Str = Double.toString(value1);
int decimalIndex = value1Str.indexOf(".");
int value1Precision = 0;
if (decimalIndex != -1) {
value1Precision = (value1Str.length() - 1) - decimalIndex;
}
String value2Str = Double.toString(value2);
decimalIndex = value2Str.indexOf(".");
int value2Precision = 0;
if (decimalIndex != -1) {
value2Precision = (value2Str.length() - 1) - decimalIndex;
}
int maxPrecision = value1Precision > value2Precision ? value1Precision : value2Precision;
sum = value1 + value2;
String s = String.format("%." + maxPrecision + "f", sum);
sum = Double.parseDouble(s);
return sum;
}
You can Do the Following!
System.out.println(String.format("%.12f", total));
if you change the decimal value here %.12f
So far I understand it as main goal to get correct double from wrong double.
Look for my solution how to get correct value from "approximate" wrong value - if it is real floating point it rounds last digit - counted from all digits - counting before dot and try to keep max possible digits after dot - hope that it is enough precision for most cases:
public static double roundError(double value) {
BigDecimal valueBigDecimal = new BigDecimal(Double.toString(value));
String valueString = valueBigDecimal.toPlainString();
if (!valueString.contains(".")) return value;
String[] valueArray = valueString.split("[.]");
int places = 16;
places -= valueArray[0].length();
if ("56789".contains("" + valueArray[0].charAt(valueArray[0].length() - 1))) places--;
//System.out.println("Rounding " + value + "(" + valueString + ") to " + places + " places");
return valueBigDecimal.setScale(places, RoundingMode.HALF_UP).doubleValue();
}
I know it is long code, sure not best, maybe someone can fix it to be more elegant. Anyway it is working, see examples:
roundError(5.6+5.8) = 11.399999999999999 = 11.4
roundError(0.4-0.3) = 0.10000000000000003 = 0.1
roundError(37235.137567000005) = 37235.137567
roundError(1/3) 0.3333333333333333 = 0.333333333333333
roundError(3723513756.7000005) = 3.7235137567E9 (3723513756.7)
roundError(3723513756123.7000005) = 3.7235137561237E12 (3723513756123.7)
roundError(372351375612.7000005) = 3.723513756127E11 (372351375612.7)
roundError(1.7976931348623157) = 1.797693134862316
Do not waste your efford using BigDecimal. In 99.99999% cases you don't need it. java double type is of cource approximate but in almost all cases, it is sufficiently precise. Mind that your have an error at 14th significant digit. This is really negligible!
To get nice output use:
System.out.printf("%.2f\n", total);

Java integer-double division confusion [duplicate]

This question already has answers here:
Integer division: How do you produce a double?
(11 answers)
Closed 7 years ago.
Program 1
int sum = 30;
double avg = sum / 4; // result is 7.0, not 7.5 !!!
VS.
Program 2
int sum= 30
double avg =sum/4.0 // Prints lns 7.5
Is this because the '4' in program 1 is acting as a literal integer? so 30/4 would give me 7. However since this data type is a double, we need to add a .0 to end. so '7.0'
Program 2 has 4.0 which is acting as a literal double. an int/double would always give double because it more precise. so we get '7.5'. I don't understand what double data type is doing to the result though.. it really doesn't need to do anything since the conditions of the double data type are already satisfied.(have the most precise result out of the computation).
Am I wrong? I encourage you to correct me! This is how I learn.. :)
In your first example:
int sum = 30;
double avg = sum / 4; // result is 7.0, not 7.5 !!!
sum is an int, and 4 is also an int. Java is dividing one integer by another and getting an integer result. This all happens before it assigns the value to double avg, and by then you've already lost all information to the right of the decimal point.
Try some casting.
int sum = 30;
double avg = (double) sum / 4; // result is 7.5
OR
int sum = 30;
double avg = sum / 4.0d; // result is 7.5
This is an integer division (because it involves two integers)
int sum = 30;
double avg = (sum / 4); // result is 7
Integer division, will round down to the nearest integer.
However, this is a double division (because 4.0 is a double)
int sum= 30
double avg = (sum/4.0) // result is 7.5
This is the expected behaviour, and the conversion are all well defined. No need to guess. Take a look at the java docs about conversion.
A widening conversion of an int or a long value to float, or of a long
value to double, may result in loss of precision - that is, the result
may lose some of the least significant bits of the value. In this
case, the resulting floating-point value will be a correctly rounded
version of the integer value, using IEEE 754 round-to-nearest mode
In java, operations involving only integer types (int, long and so on) have integer results. This includes divisions.
Both 30 and 4 are integer values, so if you try to divide them, integer division is used.
But if you try either 30.0/4 or 30/4.0 then the result will be 7.5 because you will be using floating-point division.
The declared type of the variable avg has no influence on the result. The decimal part is lost during the division, and not when you assign the value to the variable.
Image taken from : http://www.mathcs.emory.edu/~cheung/Courses/170/Syllabus/04/mixed.html
Refer above URL for more clear explanation.
PROGRAM 1
In Java, when you do a division between two integers, the result is an integer. So when you do sum/4, the result is the integer 7. Then you assign that integer to a double variable, so that 7 turns into 7.0.
PROGRAM 2
In Java, when you do a division between an integer and a double, the result is a double. So when you do sum/4.0, the result is the double 7.5. Then you assign that to a double variable, so it's still 7.5.
So the problem is not how println prints the variables, but how division works in Java

Dividing error in java language

I have a simple java program that does not operate the way that I think it should.
public class Divisor
{
public static void main(String[] args)
{
int answer = 5 / 2;
System.out.println(answer);
}
}
Why is this not printing out 2.5?
5 / 2 is integer division (you're even storing it in an integer variable), if you want it to be 2.5, you need to use floating point division:
double answer = 5.0 / 2.0;
Integer division is always going to be equal to normal mathematical division rounded down to the nearest integer.
Java has integer division which says: integer divided by integer results in integer. 2.5 cannot be represented with integer so the result is floored to 2.0. Moreover, you store the result in integer.
If you need floating point division you can cast one of operands to double and change answer type to double as well. You use literal values here, so changing 5 to 5. makes this literal value double.
In the end the following should work for you:
double answer = 5. / 2;
Note, you don't even need a zero sign after a dot symbol!

Java float not acting correctly [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why does (360 / 24) / 60 = 0 … in Java
I am having this problem:
float rate= (115/100);
When I do:
System.out.println(rate);
It gives me 1.0
What... is the problem?
115 and 100 are both integers, so will return an integer.
Try doing this:
float rate = (115f / 100f);
You're performing integer division (which provides an integer result) and then storing it in a float.
You need to use at least one float in the operation for the result to be the proper type:
float rate = 115f / 100;
float rate= (115/100);
Does the following things:
1) Performs integer division of 115 over 100 this yields the value 1.
2) Cast the result from step 1) to a float. This yields the value 1.0
What you want is this:
float rate = 115.0/100;
Or more generally, you want to convert one of the pieces of your division into a float whether that is via casting (float)115/100 or by appending a decimal point to one of the two pieces or by doing this float rate = 115f / 100 is completely up to you and yields the same result.
In order to perform floating-point arithmetic with integers you need to cast at least one of the operands to a float.
Example:
int a = 115;
int b = 100;
float rate = ((float)a)/b;
use float rate= (float)(115.0/100); instead
It is enough to put float rate = 115f / 100;
The problem you have is that your dividend and divisor are declared as integer type.
In mathematic when you divide two integer results only with remainder. And that is what you assign to your rate variable.
So to have the result as you expected, a remainder with fraction (rational numbers). Your dividend or divisor must be declared in a type with precision.
Base two known types with precision are float (Floating point) and double (Double precision).
By default all numbers (integer literals for purists) written in Java code are in type int (Integer). To change that you need to tell the compiler that a number you want to declare should be represent in different type. To do that you need to append a suffix to integer literal.
Literals for decimal types:
float - f or F; 110f;
double - d or D 110D;
Note that when you would like to use the double, type you can also declare it by adding a decimal separator to literal:
double d = 2.;
or
double d = 2.0;
I encourage you to use double type instead of float. Double type is more suitable for most of modern application. Usage of float may cause unexpected results, because of accuracy problem that in single point calculation have bigger impact on result. Good reading about this “What Every Computer Scientist Should Know About Floating-Point Arithmetic”.
In addition on current CPU architecture both float and double have same performance characteristic. So there is not need to sacrifice the accuracy.
A final note about floating point types in is that non of them should be use when we write a financial application. To have valid results in this matter, you should always used [BigDecimal]

different result in java how can it be rectified

Simple calculation gives different result in java.
int a=5363/12*5;
out.println(a);// result is 2230
But actually result should be 2234.5
How can this java result be rectified?
Two issues:
The expression 5363/12*5 gives an integer result (in particular, the division is integer).
The variable a is of type int (integer).
To fix:
double a=5363.0/12*5;
out.println(a);
Note that in general you can't expect to get exact results when using floating-point arithmetic. The following is a very good read: What Every Computer Scientist Should Know About Floating-Point Arithmetic.
5363, 12, and 5 are all being interpreted as ints. the calculation actually being performed here is:
5363/12 = 446.9… - truncated to the int value 446
446 * 5 = 2230
Try specifying a as a float, and indicate that the numbers in the calculation are also created as floats:
float a = 5363f/12f*5f
Take a as double.
Taking a as int will round it to the integer.
Because your all the literal numbers in the right hand side are integers (e.g. 5363 as opposed to 5363.0) expression is being calculated using integer arithmetic semantics i.e. / does whole number division. Thus 5262/12 equals 446 and 446*5 equals 2230. Also your variable a is an int which can only ever hold an integer value.
To fix this you need to do two things. Change the type of a to a decimal type e.g. float or double b) have at least one of 5363 and 12 represented as a decimal type e.g.
double a= 5363.0/12.0*5
Instead of using double you can re-order your expression.
Assuming 5363/12*5 = 5363*5/12 this will give you a closer answer. You have commented you want to round the result so instead you have to add half the value you are dividing by.
int a = (5363 * 5 + /* for rounding */ 6) / 12;
System.out.println(a);
prints
2235
An int is an Integer - nothing after the ..
You should be using
double a = 5363d/12*5;
It seems it has some int/double rounding issue:
double a=((double)5363/12)*5;
System.out.println("VALUE: "+a);
Prints:
VALUE: 2234.5833333333335
Edit: rounding the result to an integer value:
double a=((double)5363/12)*5;
long b=Math.round(a); //you can cast it to an int type if needed
System.out.println("ROUNDED: "+b);
Prints:
ROUNDED: 2235
Use double
double a = 5363/12*5;
System.out.println(a);
or
cast the integer, to prevent loss or precision.
int a = ((int) 5363/12*5);
System.out.println(a);

Categories