1.

Why Does Julia Give A Domainerror For Certain Seemingly-sensible Operations?

Answer»

Certain operations make mathematical sense but result in errors:

julia> sqrt(-2.0)

ERROR: DomainError with -2.0:

sqrt will only return a complex result if called with a complex argument. TRY sqrt(Complex(x)).

Stacktrace:

[...]

This behavior is an inconvenient consequence of the requirement for type-stability. In the case of sqrt, most users want sqrt(2.0) to give a REAL number, and would be unhappy if it produced the complex number 1.4142135623730951 + 0.0im. One could write the sqrt FUNCTION to switch to a complex-valued output only when passed a NEGATIVE number (which is what sqrt does in some other languages), but then the result would not be type-stable and the sqrt function would have poor performance.

In these and other cases, you can get the result you want by choosing an input type that conveys your willingness to accept an output type in which the result can be represented:

julia> sqrt(-2.0+0im)

0.0 + 1.4142135623730951im.

Certain operations make mathematical sense but result in errors:

julia> sqrt(-2.0)

ERROR: DomainError with -2.0:

sqrt will only return a complex result if called with a complex argument. Try sqrt(Complex(x)).

Stacktrace:

[...]

This behavior is an inconvenient consequence of the requirement for type-stability. In the case of sqrt, most users want sqrt(2.0) to give a real number, and would be unhappy if it produced the complex number 1.4142135623730951 + 0.0im. One could write the sqrt function to switch to a complex-valued output only when passed a negative number (which is what sqrt does in some other languages), but then the result would not be type-stable and the sqrt function would have poor performance.

In these and other cases, you can get the result you want by choosing an input type that conveys your willingness to accept an output type in which the result can be represented:

julia> sqrt(-2.0+0im)

0.0 + 1.4142135623730951im.



Discussion

No Comment Found