# How to take the derivative of a function?

**URL:** <https://discourse.julialang.org/t/how-to-take-the-derivative-of-a-function/77885>\
**Category:** New to Julia\
**Created:** [March 14, 2022, 5:43pm UTC](https://discourse.julialang.org/t/how-to-take-the-derivative-of-a-function/77885 "2022-03-14T17:43:19Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![CentraCep](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/centracep/32/32454_2.png) [@CentraCep](https://discourse.julialang.org/u/CentraCep)\
**Post date:** [March 14, 2022, 5:43pm UTC](https://discourse.julialang.org/t/how-to-take-the-derivative-of-a-function/77885/1 "2022-03-14T17:43:19Z")

</div>

Let’s say I have a function like this:

```julia
T = 10^6
η = 10^9*T^(-3/2) 
x = range(-10, 10, step=1) 
t = [0, 1, 2, 4]
B_z(x, t) = @. erf(x/sqrt(4*η*t))

```

I wanto differentiate `B_z` with respect to x and assign it to a new function called `dBdx(x, t)`. Is there a way to do this?

---

<div class="post-metadata">

**Author:** ![josuagrw](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/josuagrw/32/1015_2.png) [@josuagrw](https://discourse.julialang.org/u/josuagrw)\
**Post date:** [March 14, 2022, 5:46pm UTC](https://discourse.julialang.org/t/how-to-take-the-derivative-of-a-function/77885/2 "2022-03-14T17:46:27Z")

</div>

There are several options. A good starting point is probably

[https://github.com/JuliaDiff/ForwardDiff.jl](https://github.com/JuliaDiff/ForwardDiff.jl)

---

<div class="post-metadata">

**Author:** ![CentraCep](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/centracep/32/32454_2.png) [@CentraCep](https://discourse.julialang.org/u/CentraCep)\
**Post date:** [March 14, 2022, 6:11pm UTC](https://discourse.julialang.org/t/how-to-take-the-derivative-of-a-function/77885/3 "2022-03-14T18:11:50Z")

</div>

```julia
T = 10^6
η = 10^9*T^(-3/2) 
x = range(-10, 10, step=1) 
t = [0, 1, 2, 4]
B_z(x, t) = @. erf(x/sqrt(4*η*t))
dB_zdx(x, t) = ForwardDiff.derivative(B_z(x, t), x)

```

Ok, so I have attempted to set up the derivative as shown here. This does not seem to work as I intended though, because I expect `dB_zdx(5, 0) = 0` and `dB_zdx(0, 0) = infinity` but when I run these I have

```julia
MethodError: objects of type Float64 are not callable

```

Do you know what I may be missing here?

---

<div class="post-metadata">

**Author:** ![josuagrw](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/josuagrw/32/1015_2.png) [@josuagrw](https://discourse.julialang.org/u/josuagrw)\
**Post date:** [March 14, 2022, 6:32pm UTC](https://discourse.julialang.org/t/how-to-take-the-derivative-of-a-function/77885/4 "2022-03-14T18:32:13Z")

</div>

certainly. you need to provide the derivative method with a function of `x`, i.e.

```julia
dB_zdx(x, t) = ForwardDiff.derivative(x̃ -> B_z(x̃, t), x)

```
