Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I need to compare numbers of decimal type, where the comparison will be made up to decimal number three but with the code that I have it cannot do it.
I have tried round as well but it is not achieved either
The code is the following:
the number compare=
-3.1756 ; -3.175 this is true
3.174 ; 3.175 this is false
public static boolean areEqualByThreeDecimalPlaces(double one, double two)
int a = (int) Math.floor(one*1000);
int b = (int) Math.floor((two*1000));
if(a == b){
System.out.println(true);
System.out.println(a + "---" + b);
return true;
}
else
System.out.println(false);
System.out.println(a + "---" + b);
return false;
Since you are using floor(), you are not just truncating after the decimal point. You are moving to the next smaller integer. Since you are dealing with negative numbers here, floor(-3.1756) unexpectedly becomes -3176 (not -3175!). Thus the two numbers do not compare equal.
So to do truncation you have to use ceil() for negative numbers:
int a = (int) (one < 0 ? Math.ceil(one * 1000) : Math.floor(one*1000));
int b = (int) (two < 0 ? Math.ceil(two * 1000) : Math.floor(two*1000));
Another option might be to use rounding with a function that respects RoundingMode.DOWN.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I need a recursive method in the form of: methodName(int a, int b). The method would return 0 if a is not a multiple of b; or would return the number I need to multiply b with to get a. How can I do that without changing the parameters of the function?
You don't need to do this recursively.
multiple(int a, int b) {
return a % b == 0 ? a/b : 0;
}
For simplicity, assume dividend and divisor are positive.
When using recursion, we need following steps:
Determine Base Case, which we can easily solve the problem. For example, when dividend is less than divisor, we know dividend will not be a multiple, when dividend equals to divisor, the multiple will be 1.
Reduce to "easier" problem. This is the trickiest part. When the problem is more "close" to Base Case, it will be "easier". For this question, the problem will be easier when value of dividend is smaller, so we try to reduce dividend value. One of the possible values to reduce will be divisor, as we need to link up the "easier" problem and the "original" problem.
Merge result to "original" problem. How to merge "easier" problem result to the "original" problem? We need to think about the relation between them.
calculateMultiple(dividend, divisor) = ? + calculateMultiple(dividend - divisor, divisor)
We see that:
? will be 1 when dividend is multiple of divisor and
? will be 0 when dividend is not multiple of divisor
private static int calculateMultiple(int dividend, int divisor) {
// 1. base case
if (dividend < divisor) {
return 0;
}
if (dividend == divisor) {
return 1;
}
// 2. reduce to easier problem
int multiple = calculateMultiple(dividend - divisor, divisor);
// 3. merge result
if (multiple == 0) {
return 0;
}
return multiple + 1;
}
Of course, we can modify above method with recursion to support non positive dividend and divisor.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
For instance, I have integers, i.e. 450. I want to get 1/100 of the number N. In this case it should be 4.5, which will rounded to 5.
int i = 450;
int round = Math.round(i/450)?
When the i varies, is this safe always?
i/450 will do an integer division before the result gets passed into Math.round and you won't get what you expected. Even then you got ~1/450 of the value, not 0.01 of it. You need
(int)Math.round(i/100.0);
However you can do rounding with just integer math like either of these
int round = (i + 50)/100; // i + 99 for ceiling
int round = (i - 1)/100 + 1;
int round = i/100 + (i % 100 < 50 ? 0 : 1);
For more information read Rounding integer division (instead of truncating)
See also
How to round up integer division and have int result in Java?
How to Round Up The Result Of Integer Division
Fast ceiling of an integer division in C / C++
These are about ceiling function but you can get the idea
For it to work no matter numerator or denominator, then
BigDecimal.valueOf(450).divide(BigDecimal.valueOf(100),RoundingMode.HALF_UP);
Another way could be like
BigDecimal.valueOf(450,2).setScale(0, RoundingMode.HALF_UP);
You can convert back to int using .intValue()
That would only make sense of course when you are dealing with exact decimal math most of the time until the very end, like would be the case for financial applications.
I "think" this might be what you are looking for:
float i = 450;
int round = Math.round(i/100);
System.out.println(round);//prints 5
Division with int always rounds down so when i is an int, the expression i/100 returns 4 when i is between 400 and 499.
Alternately, you could cast to float:
int i = 450;
int round = Math.round((float)i/100);
System.out.println(round);//prints 5
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Say I had double x = 0.0/0.0;.
Is there anything I could do with x in order to get an actual number?
Dividing by itself/0/infinity? Subtracting by something? Anything like that.
You can go through each JLS chapter for each of +, -, *, / and % and you'll read
If either operand is NaN, the result is NaN.
Using the value NaN with any of those would always produce NaN.
Is there anything I could do with x in order to get an actual number?
I'm assuming you meant with the operators above.
I think, we should prevent any number divided by zero instead.
EDIT
avg = 0;
count = 0;
for (number in scores) {
avg += number;
count++;
}
if (count != 0){
return avg / count;
} else {
return 0.0;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Why performance tests fails on my solution:
class Solution {
public int solution(int X, int Y, int D) {
return (int) Math.ceil((Y-X)/(float)D);
}
}
How to improve?
Tests:
public class SolutionTest {
private Solution solution;
#Test
public void defaultTest(){
assertEquals(3, solution.solution(10,85,30));
}
#Test
public void many_jump1Test(){
assertEquals(499999998, solution.solution(-499999996,500000000,2));
}
#Before
public void init(){
solution = new Solution();
}
}
I think your solution is running into rounding errors, because of the lack of precision in a float. Your test results state that:
For the input (3, 999111321, 7) the solution returned a wrong answer (got 142730192 expected 142730189).
Given that input, let's have a look at the result of (X - Y) / D if we use a float, and if we use a double:
float f = (999111321 - 3) / 7.0f; // 1.42730192E8
double d = (999111321 - 3) / 7.0; // 1.427301882857143E8
^^
Note the rounding error on the last two digits before the decimal point. In order to avoid this and to get the right answer, you just need to cast D to a double instead of to a float in your solution.
Integer operations are by far faster, and an integer division, might be used:
(Y - X + D - 1) / D
Normally / D would give the floor value. In order to receive the ceil value add D - 1.
This saves:
A double division
Taking Math.ceil()
Converting to int
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
//I am supposed to do it with loops and decision statements, but it's not working. Help!
import java.util.Scanner;
public class main {
/**
* #param args
*/
public static void main(String[] args) {
//Declare variables
Scanner abc;
abc = new Scanner (System.in);
int input;
int divide = 2;
int count=0;
//Ask for input
System.out.println("Please enter an integer to determine if it is prime");
input = abc.nextInt();
//Do math
for (int x=1; x < input; x++) {
if ((input%divide) == 0)
count += 1;
divide = divide + 1;
}
if (count == 0)
System.out.println("It is a prime number");
else
System.out.println("It is not a prime number");
}
}
In your for loop, for the last iteration, x = input - 1, but that means divide = input (since divide was one greater in the beginning, and you increment both once per iteration of the loop), so count will actually be equal to 1 if the number is prime, not 0.
You're counting the number of divisors; all you need to do is determine if there is at least one divisor. Here's a better algorithm:
function isPrime(n)
if n is even
return n == 2
d := 3
while d * d <= n
if n % d == 0
return False
d := d + 2
return True
I discuss this algorithm, among others in the essay Programming with Prime Numbers at my blog, which includes implementations in Java.
It looks like count is supposed to count the number of factors of input not counting 1 and input. For readability, I'd recommend using a name like numOfFactors instead of count.
Given that, now look at your loop and answer these questions. I'm not going to give you the answer. (Yes, you can get the answer by looking at others' comments, but I think you will learn more by answering these questions anyway.)
(1) What are x and divide the first time you go through the loop, at the beginning of the loop?
(2) If you look at what happens to x and divide, there's a simple relationship between x and divide at the beginning of each time through the loop. What is it?
(3) What is x the last time you go through the loop?
(4) Based on the answers to #2 and #3, what is divide at the beginning of the last time through the loop? What will input%divide be equal to?
That's why it isn't working. Figure that out first. Then we can talk about how to can make it work more efficiently.
MORE: OK, I'll say one more thing. If all you care about is whether count is zero or not, you can quit your loop as soon as you find a factor. Like this:
if ((input%divide) == 0)
{
count += 1;
break;
}
(And if you do it that way, then instead of count you should use a boolean foundAFactor because all it says is whether you found a factor, not how many there are.)
But if you really want to know the exact number of factors, don't do that.
Hello do it like this:
for(int i = input-1; i > 0; i--) {
if((input % i) == 0) {
if(i == 1)
System.out.println("is a prime");
else
System.out.println("is not a prime");
break;
}
}
for (int x=2; x < input; x++) (change x=1 to x=2)
otherwise you end up trying to divide 5 by 5 to test if 5 is prime