This is so simple I can’t believe I’m having so much trouble with it.
For an analogy to what I’m after imagine a two handed clock face, where instead of 12 hours the time was between 0 and 1.
The two hands can point in any direction, provided there values are 0 to 1, for example one pointing upwards and the other diagonally down and to the left would be 0 and 0.625.
I need a c++\c# function that given the position both hands and a bool representing if the larger or smaller segment between the hands is desired returns the position half way between both hands.
For example “0.2, 0.8, false” would refer to the smaller segment between both hands and the answer would be 0.
float func(float a, float b, bool side)
{
return 0f;
}
In many cases the calculation would be simply “(a + b) * 0.5”, however when crossing 0 as in the above example it is not. It’s also not as simple as putting a single branch in like an “if”. It seems there should be a solution far more elegant than ones I’ve tried.
edit: I’ve finally solved it myself, see the code below, additionally after various others attempted the peoblem a far more elegent solution was found.
float segment_size(float a, float b, bool side)
{
float larger, smaller, c, d_smaller, d_larger;
if (a > b)
{
smaller = b;
larger = a;
}
else
{
smaller = a;
larger = b;
}
c = larger - smaller;
if (c > 0.5) {d_larger = c; d_smaller = 1 - c;} else {d_larger = 1 - c; d_smaller = c;}
return side ? d_larger : d_smaller;
}
float func(float a, float b, bool side)
{
float larger, smaller, c;
if(a > b)
{
smaller = b;
larger = a;
}
else
{
smaller = a;
larger = b;
}
c = larger - smaller;
float outf = 0, out1 = (float)((a + b) * 0.5),
out3 = (float)(smaller - (segment_size(a, b, false) * 0.5)),
out4 = (float)((smaller + larger) * 0.5);
if(out4 > 0.5) {out4 -= 0.5f;} else {out4 += 0.5f;}
if ((side == false && c <= 0.5) || (side == true && c > 0.5)) {outf = out1;}
if (side == false && c > 0.5) {outf = out3;}
if (side == true && c <= 0.5) {outf = out4;}
if(outf < 0) {outf += 1;} if(outf >= 1) {outf -= 1;}
return outf;
}
Yeah, so I got it very wrong the first time around (calculated the length of the segment instead of its halving point), and also the second time around (was kind of dodgy, so ended up deleting the answer), but bear with me.
The solution lies in the fact we’re talking about a circle here. So if we have one halving point, we can get the other by adding half of the circumference of the circle (0.5) to that.
suppose 0<=a<1, 0<=b<1
I’m pretty sure this works. And yeah, I edited it again >_>