Skip to content

Instantly share code, notes, and snippets.

@mschauer
Created November 4, 2022 15:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mschauer/ced5185512fb71b1f92a473bd1b658a0 to your computer and use it in GitHub Desktop.
Save mschauer/ced5185512fb71b1f92a473bd1b658a0 to your computer and use it in GitHub Desktop.
Dual numbers
struct Dual <: Real
value
δ
# w and Y and tag
end
Base.show(io::IO, x::Dual) = print(io, x.value, " + ", x.δ, " ϵ")
Base.:+(x::Dual, y::Dual) = Dual(x.value + y.value, x.δ + y.δ)
Base.:*(x::Dual, y::Dual) = Dual(x.value*y.value, x.δ*y.value + x.value*y.δ)
Dual(x) = Dual(x, zero(x))
Base.promote_rule(::Type{Dual},::Type{<:Real}) = Dual
Base.log(x::Dual) = Dual(log(x.value), x.δ/x.value)
Dual(x::Dual) = x
Base.:-(x::Dual) = Dual(-x.value, -x.δ)
Base.:-(x::Dual, y::Dual) = x + (-y)
Base.:/(x::Dual, y::Dual) = Dual(x.value/y.value, (x.δ*y.value - x.value*y.δ)/(y.value^2))
Base.:<(x::Dual, y::Dual) = x.value < y.value
Base.:<=(x::Dual, y::Dual) = x.value <= y.value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment