Skip to content

sin and cos inaccurate at arguments with small imaginary components #2889

Closed
@bsxfan

Description

@bsxfan

Julia version: 0.2.0

Examples of problem:

  • julia> imag(sin(complex(1,1e-20))) gives
    0.0
  • julia> imag(cos(complex(1,1e-20))) gives
    0.0

Reason: complex.jl does as a first step of its sin(z) and cos(z) implementations: u = exp(imag(z)). This becomes exactly u==1.0 for small imag(z), while the imaginary part of z is not referenced again in the rest of the implementation.

Comparison: Python and MATLAB give non-zero values.

Why this is important:
The 'complex-step differentiation' trick is a powerful and very convenient way of implementing 'forward-mode automatic differentiation'. It can be used to get extremely accurate derivatives of complicated functions, with no programmer effort. For some function f(x), we can get a very accurate derivative at x by doing something like:

  • 1e20*imag(f(complex(x,1e-20)))
    A Taylor series expansion will show why. Currectly this trick fails with Julia's complex sin and cos implementations. (It does work for log and exp).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions