牛顿拉夫森法乳胶

Newton Raphson Method LaTeX

如何在LaTeX中实现Newton Raphson方法?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
\\documentclass{article}
\\usepackage[ngerman]{babel}
\\usepackage{xfp}
\\usepackage{tikz
}

\
ewcount\\MaxIter
\
ewcount\\Counter
% the function
\
ewcommand{\\f}[1]{%
    #1%
}
% first derivation of the function
\
ewcommand{\\df}[1]{%
    1%
}
% the command
% 1. variable: max iterations
% 2. variable: start value x_0
\
ewcommand{\
ewtonRaphson
}[2][5]{
    \\Counter=0%
    \\MaxIter=#1%
    \\pgfmathsetmacro{\\x}{#2}%
    \\Loop%
}
% the loop
\
ewcommand{\\Loop}{%
    \\let\
ext= \\Loop%
    \\pgfmathsetmacro{\\tempf}{\\fpeval{\\f{\\x}}}%
    \\pgfmathsetmacro{\\tempdf}{\\fpeval{\\df{\\x}}}%
    \\pgfmathsetmacro{\\x}{\\fpeval{\\x-\\tempf/\\tempdf}}%
    \\ifnum\\Counter<\\MaxIter \\advance\\Counter by 1 \\else \\let\
ext=\
elax \\fi%
    \
ext%
}

\\begin{document}
    % set function
    \
enewcommand{\\f}[1]{%
        #1^2-2%
    }
    % set first derivation
    \
enewcommand{\\df}[1]{%
        2*#1%
    }
    % calculate
    \
ewtonRaphson[10]{0.5}
    % print
    \\pgfmathprintnumber[precision=10]{\\x}
\\end{document
}