AJ.
AJ.

Reputation: 11240

Calculating the two x coordinates at edge of circle for a specific y coordinate

How do I find the two opposite x coordinates at the edge of a circle for a specific y coordinate?

A y coordinate of zero means the center of the circle so the two x coordinates would be +- radius

A y coordinate equaling the radius would give two x coordinates of zero.

I'm using Javascript but any language solution is fine.

Upvotes: 1

Views: 122

Answers (2)

Blindman67
Blindman67

Reputation: 54026

The existing answer though technically correct is hugely inefficient. The pattern used creates 2 Arrays every call, and repeats the full calculation twice even though the second result is a simple negative of the first (2 rather than 1 square root operations).

The following is 14 times (1400%) faster

const circleXForY = (y, r) => [y = (1 - (y / r) ** 2) ** 0.5 * r, -y];

If you include the fact that the result can also be NaN when y > r then the above function is a staggering 196 times (19,600%) quicker when y > r || y < -r.

A further slight improvement is to just use the positive result

const circleXForY = (y, r) => (1 - (y / r) ** 2) ** 0.5 * r;

The reason I posted a faster version is that this function is very often used when scanning lining circles for graphical like content presentation. I such cases performance is critical.

Upvotes: 0

Yevhen Horbunkov
Yevhen Horbunkov

Reputation: 15530

Assuming you're talking about circle placed at (0,0) (described by equation x²+y²=R²) and you need to return pair of (symmetric) x coordinates based on y and R, that would be something, like:

const getX = (y, R) => [1, -1].map(n => n*(R**2-y**2)**0.5)

Following is a quick proof-of-a-concept live-demo:

const getX = (y, R) => [1, -1].map(n => n*(R**2-y**2)**0.5)

console.log(getX(0,1))
console.log(getX(1,1))
console.log(getX(-1,1))
console.log(getX(0.7071,1))
.as-console-wrapper{min-height:100%;}

If arbitrary circle center ((x0,y0)) is considered ((x-x0)²+(y-y0)²=R²), more generic solution should work:

const getX = (y, R, x0, y0) => [1, -1].map(n => n*(R**2-(y-y0)**2)**0.5+x0)

Upvotes: 1

Related Questions