# ND and D yielding strange results

Both of the following codes, using ND and D, differentiates my function Flux[] incorrectly. If the derivatives are plotted, it can be seen that both are the original function multiplied by some constant, one positive and the other negative.

Needs[“NumericalCalculus`”];
Needs[“DifferentialEquations`NDSolveProblems`”];
Needs[“DifferentialEquations`NDSolveUtilities`”];

mu0=4Pi*10^-7;
r1=0.3;
r2=1;
n=1;
q=1;
q0=10;
m=1;
ro=1;
step=0.1;
l=10^-3;
res=1;
ca=10^-3;
period=2Pi/(4*(1/(l*ca)-(res/(2*l))^2)^(0.5));

I0[t_]=-D[q0*Exp[-t*res/(2*l)]*Cos[(1/(l*ca)-(res/(2*l))^2)^(0.5)*t],t];
B[r_,s_,t_]=(mu0*98/(2Pi*r2))*I0[t]*(1-(r*Sin[s]/r1)^2)^0.5/(2Pi*(r2-r1*Cos[s]));

Flux[r0_?NumericQ,t_?NumericQ]:=NIntegrate[B[r,s,t]*r,{s,0,2Pi},{r,0,r0},AccuracyGoal->3,PrecisionGoal->3,Method->”Trapezoidal”];

Show[Plot[q0*Exp[-t*res/(2*l)]*Cos[(1/(l*ca)-(res/(2*l))^2)^(0.5)*t],{t,0,4*period},PlotRange->All,PlotStyle->Green],Plot[q0*Exp[-t*res/(2*l)],{t,0,4*period},PlotRange->All,PlotStyle->{Purple,Dashed}],Plot[-q0*Exp[-t*res/(2*l)],{t,0,4*period},PlotRange->All,PlotStyle->{Purple,Dashed}],Plot[q0*Cos[(1/(l*ca)-(res/(2*l))^2)^(0.5)*t],{t,0,4*period}],AxesLabel->{t,Charge}]
Plot[I0[t],{t,0,4*period},AxesLabel->{t,Current},PlotStyle->Orange]
Plot[Flux[0.2,t],{t,0,4*period},AxesLabel->{t,Flux}]
Plot[D[Flux[0.2,t],t]/.t->t0,{t0,0,4*period},PlotStyle->Red,AxesLabel->{t,Emf}]
period

and

Plot[ND[Flux[0.2,t],t,t0],{t0,0,4*period},PlotStyle->Red,AxesLabel->{t,Emf}]

If I plug in a simple polynomial to B[], plots appear to be correct. I would appreciate if you could spot the mistake for me,

Thank you.

=================

=================

1

=================

What about explicitly differentiating under the integral sign?

dFlux[r0_?NumericQ, t_?NumericQ] :=
NIntegrate[
Derivative[0, 0, 1][B][r, s, t]*r, {s, 0, 2 Pi}, {r, 0, r0},
AccuracyGoal -> 3, PrecisionGoal -> 3, Method -> “Trapezoidal”];

Plot[Flux[0.2, t], {t, 0, 4*period}, AxesLabel -> {t, Flux}]

Plot[dFlux[0.2, t], {t, 0, 4*period}, PlotStyle -> Red,
AxesLabel -> {t, Emf}]