|
-
February 21st, 2010, 10:14 PM
#1
Easy - Find the closest number
How do I find the number in a loop that is the closest to another given number.
For example: I have a simple loop that prints the numbers on the console. While for loop is working I want to find the number that is closest to 20.
I believe I have to use abs() in my loop to find the absolute value of the number and then subtract this number by 20, the smallest number is the closest. Is that right? But how do I compare the abs() value each time in the loop? Thanks for the answers.
-
February 21st, 2010, 11:36 PM
#2
Re: Easy - Find the closest number
Do I understand correctly that you're essentially doing a closest-point query, eg, you have a list of numbers (1-D points) and you wish to know which of them an additional number is closest to?
If so, and your set is {N} and the query is X, just minimize abs(N - X).
-
February 22nd, 2010, 03:07 PM
#3
Re: Easy - Find the closest number
Thanks for the answer Lindley.
I don't quite understand what you meant by minimize abs().
This is what I do.
In the loop:
value = abs(20-query)
The smallest result is the closest value.
when loop starts over I need to compare the result with the new generated result. If it is greater than previous result skip it otherwise change it and store the smallest result until the end. I don't know how I can accomplish this.
-
February 22nd, 2010, 03:26 PM
#4
Re: Easy - Find the closest number
It's not complicated.
Code:
if (newresult > maxresult)
maxresult = newresult
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|