views:

201

answers:

2

I'm currently in the throes of writing a system based on subdividing space (it's for a game), I need to be able to test if a circle completely contains a square.

For bonus points, I should point out that my system works in N dimensions, so if your algorithm works by looping through each dimension and doing something, present it as such ;)

+1  A: 
// lower and upper are opposite corners (e.g. min and max for each dimension)
within(center,radius,lower,upper):
  maxsq<-radius^2
  sumsq<-0
  for c<-0 to N-1
     dl=(center[c]-lower[c])^2
     du=(center[c]-upper[c])^2
     sumsq<-sumsq+max(dl,du)
     if sumsq > maxsq return false
  return true

You may want to store maxsq for the sphere rather than recomputing it every time (a very minor expense).

wrang-wrang
Well the circle/square example was just a simple example of the 2D case which most people are best at thinking in ;)And that really was fairly easy wasn't it >_<
Martin
This doesn't work in this situation:http://img35.imageshack.us/i/51141280.jpg/
Martin
Wow, I can't believe how dumb I was there :) Obviously, if you check all the corners, you're golden, but there are 2^N of them!
wrang-wrang
hehe that's ok, I actually implemented it before I realised it was wrong xD
Martin
+6  A: 

Of the 2^N corners, you only need to check that the furthest corner from the center of the hypersphere is inside the hypersphere.

So:

distance = 0
for each dimension D:
    a = abs(coordinate of sphere center in D - min coordinate of cube in D)
    b = abs(coordinate of sphere center in D - max coordinate of cube in D)
    distance += max(a,b)^2
if distance <= radius*radius then cube is in sphere.
jcd
Exactly, this is the right way to do it. If you know the center c' of the cube, and its half-side length h, then this condition can be written asd(c, c') + sqrt(dim*h^2) < radius
Camille
I just thought of this last night as I was going to sleep and figured it would be safe until morning :) Well done.
wrang-wrang
Camille, I don't think that's right except if the cube center is on a diagonal compared to the circle center. It's true that h*sqrt(N) is the radius of the circumsphere containing the cube, but considering cubes that are just inside the sphere (one of the corners just misses touching the boundary), unless the center of the cube is colinear with the radius to that corner, the sum is greater than the radius.
wrang-wrang