@@ -33,9 +33,7 @@ Take for example a prototypical small nonlinear solver code in its out-of-place
33
33
``` @example small_opt
34
34
using NonlinearSolve
35
35
36
- function f(u, p)
37
- u .* u .- p
38
- end
36
+ f(u, p) = u .* u .- p
39
37
u0 = [1.0, 1.0]
40
38
p = 2.0
41
39
prob = NonlinearProblem(f, u0, p)
@@ -53,9 +51,7 @@ using BenchmarkTools
53
51
Note that this way of writing the function is a shorthand for:
54
52
55
53
``` @example small_opt
56
- function f(u, p)
57
- [u[1] * u[1] - p, u[2] * u[2] - p]
58
- end
54
+ f(u, p) = [u[1] * u[1] - p, u[2] * u[2] - p]
59
55
```
60
56
61
57
where the function ` f ` returns an array. This is a common pattern from things like MATLAB's
@@ -71,7 +67,7 @@ by hand, this looks like:
71
67
function f(du, u, p)
72
68
du[1] = u[1] * u[1] - p
73
69
du[2] = u[2] * u[2] - p
74
- nothing
70
+ return nothing
75
71
end
76
72
77
73
prob = NonlinearProblem(f, u0, p)
@@ -84,6 +80,7 @@ the `.=` in-place broadcasting.
84
80
``` @example small_opt
85
81
function f(du, u, p)
86
82
du .= u .* u .- p
83
+ return nothing
87
84
end
88
85
89
86
@benchmark sol = solve(prob, NewtonRaphson())
@@ -114,6 +111,7 @@ to normal array expressions, for example:
114
111
115
112
``` @example small_opt
116
113
using StaticArrays
114
+
117
115
A = SA[2.0, 3.0, 5.0]
118
116
typeof(A)
119
117
```
@@ -135,22 +133,20 @@ want to use the out-of-place allocating form, but this time we want to output a
135
133
array. Doing it with broadcasting looks like:
136
134
137
135
``` @example small_opt
138
- function f_SA(u, p)
139
- u .* u .- p
140
- end
136
+ f_SA(u, p) = u .* u .- p
137
+
141
138
u0 = SA[1.0, 1.0]
142
139
p = 2.0
143
140
prob = NonlinearProblem(f_SA, u0, p)
141
+
144
142
@benchmark solve(prob, NewtonRaphson())
145
143
```
146
144
147
145
Note that only change here is that ` u0 ` is made into a StaticArray! If we needed to write
148
146
` f ` out for a more complex nonlinear case, then we'd simply do the following:
149
147
150
148
``` @example small_opt
151
- function f_SA(u, p)
152
- SA[u[1] * u[1] - p, u[2] * u[2] - p]
153
- end
149
+ f_SA(u, p) = SA[u[1] * u[1] - p, u[2] * u[2] - p]
154
150
155
151
@benchmark solve(prob, NewtonRaphson())
156
152
```
0 commit comments