It's not possible, and probably more importantly, probably wouldn't be useful even if you could do it.
Since the function can return a complex number, the calling code needs to be prepared to process a complex number. If your code needs to be able to process complex numbers in any case, it almost certainly makes more sense to always return a complex number, and if the input was positive it'll be of the form X + 0i
(i.e., the imaginary part will equal 0).
In theory, you could do this in a language that supported dynamic typing -- but even with most of them, sqrt
is basically statically typed. If the input you provide is a real number, the result will also be a real number, and if the input was negative the result will typically be a NaN
or something on that order. If (and only if) you provide the input as a complex number will you receive a complex number as the result.