CS代考

# Dual(a,b) represents a + b*ϵ

Copyright By PowCoder代写 加微信 powcoder

struct Dual{T}

const ϵ = Dual(0,1)

import Base: +, -, ^, /, *, exp, sin

+(x::Real, y::Dual) = Dual(x + y.a, y.b)
+(x::Dual, y::Real) = Dual(x.a + y, x.b)
+(x::Dual, y::Dual) = Dual(x.a + y.a, x.b + y.b)
-(x::Real, y::Dual) = Dual(x – y.a, -y.b)
-(x::Dual, y::Real) = Dual(x.a – y, x.b)
-(x::Dual, y::Dual) = Dual(x.a – y.a, x.b – y.b)

/(x::Dual, y::Real) = Dual(x.a/y, x.b/y)
*(x::Dual, y::Dual) = Dual(x.a*y.a, x.a*y.b + x.b*y.a)

function ^(x::Dual, k::Integer)
error(“Not implemented”)
elseif k == 1
else # k > 1
Dual(x.a^k, k* x.b * x.a^(k-1))

exp(x::Dual) = Dual(exp(x.a), x.b*exp(x.a))
sin(x::Dual) = Dual(sin(x.a), x.b*cos(x.a))

sin (generic function with 14 methods)

f = x -> 1 + x + x^2
g = x -> 1 + x/3 + x^2

f(1 + ϵ).b # f'(1) == 3
g(1 + ϵ).b

2.3333333333333335

f = x -> (x-1)*(x-2) + x^2

Dual{Int64}(4, 5)

f = x -> exp(x^2 * sin(x) + x)

Dual{Float64}(71.52736276745335, -505.2129571436543)

exp(9sin(3) + 3) * (9cos(3) + 6sin(3)+1)

-505.2129571436543

# 1 + … + x^n

function s(n, x)
ret = 1 + x
for k = 2:n
ret = ret + x^k

s(10, 1 + ϵ)

Dual{Int64}(11, 55)

程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com