-
Notifications
You must be signed in to change notification settings - Fork 0
/
traj.out
84 lines (72 loc) · 2.4 KB
/
traj.out
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
pqR version 2.15.1 (2020-07-23), based on R 2.15.0 (2012-03-30)
R 2.15.0 is Copyright (C) 2012 The R Foundation for Statistical Computing
ISBN 3-900051-07-0
Modifications to R in pqR are Copyright (C) 2013-2020 Radford M. Neal
Some modules are from R-2.15.1 or later versions distributed by the R Core Team
Platform: x86_64-apple-darwin17.7.0 (64-bit)
R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.
Natural language support but running in an English locale
R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.
Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.
No helper threads, task merging enabled, uncompressed pointers.
> # Find the distance travelled by a projectile launched on level
> # ground with initial velocity (vx,vy), with no air resistance.
>
> distance_travelled <- function (vx, vy, dt=0.0001, g=9.8) {
+ x <- y <- 0
+ repeat {
+ last_x <- x
+ last_y <- y
+ x <- x + vx*dt
+ y <- y + vy*dt
+ if (y < 0) # return impact x location, interpolating
+ return ((x*last_y - last_x*y) / (last_y-y))
+ vy <- vy - g*dt
+ }
+ }
>
>
> # See the derivative of distance with respect to angle of launch for
> # angles of 40 and 60 degrees.
>
> with gradient (a = 40 * pi/180) distance_travelled (cos(a), sin(a))
[1] 0.1005672
attr(,"gradient")
[1] 0.03543097
> with gradient (a = 60 * pi/180) distance_travelled (cos(a), sin(a))
[1] 0.08841993
attr(,"gradient")
[1] -0.1021333
>
>
> # Find angle of launch maximizing distance, for fixed initial speed.
> # Note that nlm minimizes, so we negate the distance.
>
> system.time(print(
+ nlm (function (a)
+ with gradient (a) -distance_travelled (cos(a), sin(a)),
+ 0) $ estimate * 180/pi
+ ))
[1] 44.99701
user system elapsed
0.099 0.007 0.106
>
>
> # For this simple example with only one variable, optimizing without
> # the gradient information is about as fast...
>
> system.time(print(
+ nlm (function (a)
+ -distance_travelled (cos(a), sin(a)),
+ 0) $ estimate * 180/pi
+ ))
[1] 44.99701
user system elapsed
0.071 0.000 0.072
>