Nearest Number

Blitz3D Forums/Blitz3D Beginners Area/Nearest Number

I am scratching my head again :-)

I have two numbers, X and Y, and know that X is greater than Y. I have a third number NUM that I know is somewhere between X and Y (it could also equal X or Y).

What is the best way of seeing which of the two numbers X and Y NUM is nearest to?

difference=(X-NUM-Y)

If difference>(X-Y/2) then Print "Closer to Y"
If difference<=(X-Y/2) then Print "Closer to X"

(I think - bit tired)

Thank you, Kind sir!

Try it first :) I cannot test it as I am at work right now!

Hi Malice,

it doesn't quite work I think. I put together a simple test programme as follows:

While Not KeyHit(57)

X=Input("What is the high number?")
Y=Input("What is the low number?")
NUM=Input("what is the middle number?")

difference=(X-NUM-Y)

If difference>(X-Y/2) Then Print NUM+" is closer to "+Y+" than "+X
If difference<=(X-Y/2) Then Print NUM+" is closer to "+X+" than "+Y

Print ""
Print ""
Print ""
Wend

and it tends to default to the bigger number.

Okay - sorry got them wrong way round...

Also added the equals part!

While Not KeyHit(57) 

X=Input("What is the high number?") 
Y=Input("What is the low number?") 
NUM=Input("what is the middle number?") 

difference=(X-NUM-Y) 

If difference>(Y-X/2) Then Print NUM+" is closer to "+Y+" than "+X 
If difference<(Y-X/2) Then Print NUM+" is closer to "+X+" than "+Y 

If difference=(Y-X/2) Then Print NUM+" is exactly between "+X+" and "+Y

Print "" 
Print "" 
Print "" 
Wend 


Oh and it breaks if :

X-Y=1
and
NUM=Y

Isn't it just...

While Not KeyHit(1)
x=Input("High Number ")
y=Input("Low Number ")
num=Input("Middle Number ")
If (x-num<num-y) Then Print "X is nearer"
If (x-num>num-y) Then Print "Y is nearer"
If (x-num=num-y) Then Print "They are both as close"
Print
Wend


and use floats if you want it to not break when x-y=1

This returns the number that 'NUM' is nearest to, or 0 if the difference between each number and NUM is equal:
Function NearestTo(X,Y,NUM)
	If Abs(x-num) < Abs(y-num)
		Result = X
	ElseIf Abs(x-num) > Abs(y-num)
		Result = Y
	ElseIf Abs(x-num) = Abs(y-num)
		Result = 0
	EndIf
	Return result
End Function


Thanks to both Malice and Shambler. Job done! :-)

A little variation based on finding the midpoint and then seeing which side of it NUM lies on...

While Not KeyHit(57) 

X=Input("What is the high number?") 
Y=Input("What is the low number?") 
NUM=Input("what is the middle number?") 

difference=(X-NUM-Y) 

midpoint# = (X + Y)/2.0

ComparePosition# = midpoint#-NUM

If ComparePosition<0 Then
   Print NUM+" is closer to "+Y+" than "+X 
Else
   If ComparePosition > 0 Then
      Print NUM+" is closer to "+X+" than "+Y 
   Else
	  Print NUM+" is exactly between "+X+" and "+Y
   EndIf
EndIf

Print "" 
Print "" 
Print "" 
Wend