I want to get two ints, one divided by the other to get a decimal or percentage.
How can I get a percentage or decimal of these two ints?
(I'm not sure if it is right.. I'm probably way off...)
for example:
int correct = 25;
int questionNum = 100;
float percent = correct/questionNum *100;
This is how I thought I could do it, but it didn't work... I want to make the decimal (if there is one) into a percent out of 100 for example in this case it is %25. any ideas anyone?
Here is the correct code (thanks to Salvatore Previti!):
float correct = 25;
float questionNum = 100;
float percent = (correct * 100.0f) / questionNum;
(btw, I am making a project using this for a quiz checking program that is why I need the percentage or decimal)
If you don't add .0f it will be treated like it is an integer, and an integer division is a lot different from a floating point division indeed :)
float percent = (n * 100.0f) / v;
If you need an integer out of this you can of course cast the float or the double again in integer.
int percent = (int)((n * 100.0f) / v);
If you know your n value is less than 21474836 (that is (2 ^ 31 / 100)), you can do all using integer operations.
int percent = (n * 100) / v;
If you get NaN is because wathever you do you cannot divide for zero of course... it doesn't make sense.
Two options:
Do the division after the multiplication:
int n = 25;
int v = 100;
int percent = n * 100 / v;
Convert an int to a float before dividing
int n = 25;
int v = 100;
float percent = n * 100f / v;
//Or:
// float percent = (float) n * 100 / v;
// float percent = n * 100 / (float) v;
One of them has to be a float going in. One possible way of ensuring that is:
float percent = (float) n/v * 100;
Otherwise, you're doing integer division, which truncates the numbers. Also, you should be using double unless there's a good reason for the float.
The next issue you'll run into is that some of your percentages might look like 24.9999999999999% instead of 25%. This is due to precision loss in floating point representation. You'll have to decide how to deal with that, too. Options include a DecimalFormat to "fix" the formatting or BigDecimal to represent exact values.
float percent = (n / (v * 1.0f)) *100
Related
Here are the expressions I'm working with:
float firstValue = (float) (5 / 2); //output is 2.0
float secondValue = (float) 5 / 2; //output is 2.5
I'm stumped here and can't figure out why this type casting is returning two different values. I understand I can just do (5f / 2f) but I wanted to experiment using the other type casting with an expression. Why is firstValue 2.0 and secondValue 2.5? Where did the .5 go?
As brackets have the highest precedence, they get solved first
float firstValue = (float) (5 / 2); // division of integers
= (float) (2); // 5/2 = 2 , as Integers are being divided
= 2f
float secondValue = (float) 5 / 2; // division of float with integer
= ((float) 5) / 2;
= 5f / 2; // second value is equivalent to this
= 2.5f // as Float divided by Integer is Float
The first is integer math. This
float firstValue = (float) (5 / 2);
First divides five by two and gets two. Then it converts two to 2.0. The second is floating point math.
float secondValue = 5f / 2;
Which is 2.5 (and a float). Because a float divided by an int is a float.
float firstValue = (float) (5 / 2); // division of integers
The first step is to do 5/2 calculation.Then the answer is given in float.If you explain further 5 and 2 are int numbers. After calculating the int for two int numbers, the final answer is returned by int. Here the final int answer (2) is converted to a float answer. That is, wider conversion is used here. So the final answer is the integer value(2) shown in float form(2.0).
2.float secondValue = (float) 5 / 2; //output is 2.5
Since the first value(5) is named a float number, the final answer is the decimal itself
I am trying to calculate sine of an angle without using the Math.sin(). I got stuck in it's equation as I keep getting the wrong results
note I have a method that changes the angle from degrees to radians
public static double sin(double x, int precision) {
//this method is simply the sine function
double answer = 1, power = 1;
int n = 2,factorial = 1;
while (n<=precision) {
power = (power * x * x *-1) +1 ;
factorial = (factorial * (n +1))* (n-1);
answer = answer + ((power/factorial ));
n = n + 2;
}
return answer;
}
It looks like you're attempting to calculate the sine of angle given in radians using the Maclaurin series, a special case of Taylor series.
sin(x) = x - x^3/3! + x^5/5! - x^7/7! + ...
Your initial answer is 1 when it should be x. Your initial power is 1 when it should be x also.
double answer = x, power = x;
For some reason you're adding one to the power part of the result when you shouldn't be.
power = (power * x * x * -1);
You'll also need to fix your factorial calculation. Multiply by n + 1 and n, not n + 1 and n - 1.
factorial = (factorial * (n + 1)) * (n);
With these fixes, testing:
for (double angle = 0; angle <= Math.PI; angle += Math.PI / 4)
{
System.out.println("sin(" + angle + ") = " + sin(angle, 10));
}
The results are pretty good considering the limitations of precision for floating point arithmetic.
sin(0.0) = 0.0
sin(0.7853981633974483) = 0.7071067811796194
sin(1.5707963267948966) = 0.999999943741051
sin(2.356194490192345) = 0.7070959900908971
sin(3.141592653589793) = -4.4516023820965686E-4
Note that this will get more inaccurate as the values of x get larger, not just because of the inaccuracy to represent pi, but also because of the floating point calculations for adding and subtracting large values.
Is there a Java operator that would create a value equal to count but in fewer lines?
double theta = //Some value;
int count = 0;
while (theta > 0) {
theta -= pi * (1.0 / 8.0);
count += 1;
}
You've just implemented division by repeated subtraction.
So, if you had actual real numbers in Java, you could do ...
int result = (int) (theta / (Math.PI / 8)) + 1;
... to get the same result. However due to repeated rounding errors in your code, that has many more steps than a simple division, the answers will diverge a bit. The results will be the same for thetas up to around 55 million.
The rounding errors are there because float and double are not accurate representations of real numbers.
See also: Is floating point math broken?
Assuming theta > 0, something like this should work:
int count = (int)Math.ceil (theta/(Math.PI * (1.0 / 8.0)));
or
int count = (int)Math.ceil (theta*8/Math.PI);
How about this: Math.ceil( theta/(pi * (1.0 / 8.0)))?
i seen to be having a problem with the line:
int xPos = ((x / maxX) * X_AXIS_LENGTH) + X_AXIS_OFFSET; =
for testing purposes i have assigned:
int x = 10;
int maxX = 52;
but when used in this calculation x / maxX gives me 0 instead of 0.19!
http://s12.postimage.org/uawn8b6l9/image.png
You're doing integer division here:
x / maxX
Integer division will truncate the fractional part.
Cast one of the parameters to floating-point to fix it:
(double)x / maxX
You might also want to store the whole thing into a double instead of int:
double xPos = (((double)x / maxX) * X_AXIS_LENGTH) + X_AXIS_OFFSET;
Both of the operands for / are integers, so it's performing integer arithmetic. Options:
Use floating point arithmetic:
double xPos = (((double) x / maxX) * X_AXIS_LENGTH) + X_AXIS_OFFSET;
Multiply before the division, and you can still do everything in integer arithmetic, although you'll need to beware of overflow:
int xPos = ((x * X_AXIS_LENGTH) / maxX) + X_AXIS_OFFSET;
Integer division did it to you.
If you expect a floating point value, do it this way:
double ratio = ((double)x)/maxX;
That int type all the way though is a problem. I'd put more thought into that. Where do you want to truncate the fractional part?
xPos should be declared as double, not an integer. Otherwise, the data after the decimal point is truncated.
I have two integers x and y. I need to calculate x/y and as outcome I would like to get float. For example as an outcome of 3/2 I would like to have 1.5. I thought that easiest (or the only) way to do it is to convert x and y into float type. Unfortunately, I cannot find an easy way to do it. Could you please help me with that?
You just need to cast at least one of the operands to a float:
float z = (float) x / y;
or
float z = x / (float) y;
or (unnecessary)
float z = (float) x / (float) y;
// The integer I want to convert
int myInt = 100;
// Casting of integer to float
float newFloat = (float) myInt
You shouldn't use float unless you have to. In 99% of cases, double is a better choice.
int x = 1111111111;
int y = 10000;
float f = (float) x / y;
double d = (double) x / y;
System.out.println("f= "+f);
System.out.println("d= "+d);
prints
f= 111111.12
d= 111111.1111
Following #Matt's comment.
float has very little precision (6-7 digits) and shows significant rounding error fairly easily. double has another 9 digits of accuracy. The cost of using double instead of float is notional in 99% of cases however the cost of a subtle bug due to rounding error is much higher. For this reason, many developers recommend not using floating point at all and strongly recommend BigDecimal.
However I find that double can be used in most cases provided sensible rounding is used.
In this case, int x has 32-bit precision whereas float has a 24-bit precision, even dividing by 1 could have a rounding error. double on the other hand has 53-bit of precision which is more than enough to get a reasonably accurate result.
You just need to transfer the first value to float, before it gets involved in further computations:
float z = x * 1.0 / y;
Here is how you can do it :
public static void main(String[] args) {
// TODO Auto-generated method stub
int x = 3;
int y = 2;
Float fX = new Float(x);
float res = fX.floatValue()/y;
System.out.println("res = "+res);
}
See you !
Sameer:
float l = new Float(x/y)
will not work, as it will compute integer division of x and y first, then construct a float from it.
float result = (float) x / (float) y;
Is semantically the best candidate.