Design a function f such that:
f(f(x)) == 1/x
Where x is a 32 bit float
Or how about
Given a function f, find a function g such that
f(x) == g(g(x))
Interview question: f(f(n)) == -n
If f(x) == g(g(x))
, then g
is known as the functional square root of f
. I don't think there's closed form in general even if you allow x to be complex (you may want to go to mathoverflow to discuss :) ).
For the first part: this one is more trivial than f(f(x)) = -x, IMO:
float f(float x)
{
return x >= 0 ? -1.0/x : -x;
}
The second part is an interesting question and an obvious generalization of the original question that this question was based on. There are two basic approaches:
Well, here's the C quick hack:
extern double f(double x);
double g(double x)
{
static int parity = 0;
parity ^= 1;
return (parity ? x : f(x));
}
However, this breaks down if you do:
a = g(4.0); // => a = 4.0, parity = 1
b = g(2.0); // => b = f(2.0), parity = 0
c = g(a); // => c = 4.0, parity = 1
d = g(b); // => d = f(f(2.0)), parity = 0
In general, if f is a bijection f : D → D, what you need is a function σ that partitions the domain D into A and B such that:
Then, you can define g thusly:
This works b/c
You can see from Miles answer that, if we ignore 0, then the operation σ(x) = -x works for f(x) = 1/x. You can check 1-6 (for D = nonzero reals), with A being the positive numbers, and B being the negative numbers yourself. With the double precision standard, there's a +0
, a -0
, a +inf
, and a -inf
, and these can be used to make the domain total (apply to all double precision numbers, not just the nonzero).
The same method can be applied to the f(x) = -1 problem - the accepted solution there partitions the space by the remainder mod 2, using σ(x) = (x - 1), handling the zero case specially.
I like the javascript/lambda suggestion from the earlier thread:
function f(x)
{
if (typeof x == "function")
return x();
else
return function () {return 1/x;}
}
The other solutions hint at needing extra state. Here's a more mathematical justification of that:
let f(x) = 1/(x^i)= x^-i
(where ^ denotes exponent, and i is the imaginary constant sqrt(-1) )
f(f(x)) = (x^-i)^-i) = x^(-i*-i) = x^(-1) = 1/x
So a solution exists for complex numbers. I don't know if there is a general solution sticking strictly to Real numbers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With