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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
//! # Special Functions of Mathematics
//!
//! Special mathematical functions related to the beta and gamma functions.
//!
//! ## Arguments
//!
//! * a, b: non-negative numeric
//! * x, n: numeric
//! * k, deriv: integer
//!
//! ## Details
//!
//! The functions beta and lbeta return the beta function and the natural logarithm of the beta
//! function,
//!
//! $B(a,b) = \Gamma(a)\Gamma(b)/\Gamma(a+b)$.
//!
//! The formal definition is
//!
//! $\int_0^1 t^{a-1} (1-t)^{b-1} dt$
//!
//! (Abramowitz and Stegun section 6.2.1, page 258). Note that it is only defined in R for
//! non-negative a and b, and is infinite if either is zero.
//!
//! The functions gamma and lgamma return the gamma function Γ(x) and the natural logarithm of
//! the absolute value of the gamma function. The gamma function is defined by (Abramowitz and Stegun section 6.1.1, page 255)
//!
//! $\gamma(x) = \int_0^\infty t^{x-1} \text{exp}(-t) dt$
//!
//! for all real x except zero and negative integers (when NaN is returned). There will be a
//! warning on possible loss of precision for values which are too close (within about 1e-8)
//! to a negative integer less than -10.
//!
//! factorial(x) (x! for non-negative integer x) is defined to be gamma(x+1) and lfactorial to be
//! lgamma(x+1).
//!
//! The functions digamma and trigamma return the first and second derivatives of the logarithm
//! of the gamma function. psigamma(x, deriv) (deriv >= 0) computes the deriv-th derivative of $\psi(x)$.
//!
//! $digamma(x) = \psi(x) = \frac{d}{dx}\{ln \Gamma(x)\} = \Gamma'(x) / \Gamma(x)$
//!
//! \psi and its derivatives, the psigamma() functions, are often called the ‘polygamma’ functions,
//! e.g. in Abramowitz and Stegun (section 6.4.1, page 260); and higher derivatives (deriv = 2:4)
//! have occasionally been called ‘tetragamma’, ‘pentagamma’, and ‘hexagamma’.
//!
//! The functions choose and lchoose return binomial coefficients and the logarithms of their
//! absolute values. Note that choose(n, k) is defined for all real numbers n and integer k.
//! For $k ≥ 1$ it is defined as $n(n-1)…(n-k+1) / k!$, as 1 for $k = 0$ and as 0 for negative k.
//! Non-integer values of k are rounded to an integer, with a warning.
//!
//! choose(*, k) uses direct arithmetic (instead of \[l\]gamma calls) for small k, for speed and
//! accuracy reasons. Note the function combn (package utils) for enumeration of all possible
//! combinations.
//!
//! The gamma, lgamma, digamma and trigamma functions are internal generic primitive functions:
//! methods can be defined for them individually or via the Math group generic.
//!
//! ## Source
//!
//! gamma, lgamma, beta and lbeta are based on C translations of Fortran subroutines by W.
//! Fullerton of Los Alamos Scientific Laboratory (now available as part of SLATEC).
//!
//! digamma, trigamma and psigamma are based on
//!
//! Amos, D. E. (1983). A portable Fortran subroutine for derivatives of the psi function,
//! Algorithm 610, ACM Transactions on Mathematical Software 9(4), 494–502.
//!
//! ## References
//!
//! Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth &
//! Brooks/Cole. (For gamma and lgamma.)
//!
//! Abramowitz, M. and Stegun, I. A. (1972) Handbook of Mathematical Functions. New York: Dover.
//! https://!en.wikipedia.org/wiki/Abramowitz_and_Stegun provides links to the full text which is
//! in public domain.
//! Chapter 6: Gamma and Related Functions.
//!
//! ## See Also
//!
//! Arithmetic for simple, sqrt for miscellaneous mathematical functions and Bessel for the real
//! Bessel functions.
//!
//! For the incomplete gamma function see pgamma.
//!
//! ## Examples
//!
//! Basic Usage:
//! ```rust
//! # use r2rs_nmath::func::*;
//! # use strafe_type::FloatConstraint;
//! # use std::{fs::File, io::Write};
//! println!("{}", choose(5, 2));
//! println!("{:e}", factorial(100).unwrap());
//! println!("{}", lfactorial(10000));
//! # let mut f = File::create("src/func/betagam/doctest_out/betagam.md").unwrap();
//! # writeln!(f, "```output").unwrap();
//! # writeln!(f, "{}", choose(5, 2)).unwrap();
//! # writeln!(f, "{:e}", factorial(100).unwrap()).unwrap();
//! # writeln!(f, "{}", lfactorial(10000)).unwrap();
//! # writeln!(f, "```").unwrap();
//! ```
//!
//! Pascal's Triangle:
//! ```rust
//! # use r2rs_nmath::func::choose;
//! # use strafe_type::FloatConstraint;
//! # use std::{fs::File, io::Write};
//! for n in 0..=10 {
//! for i in 0..=n {
//! print!("{} ", choose(n, i))
//! }
//! println!();
//! }
//! # let mut f = File::create("src/func/betagam/doctest_out/pascal.md").unwrap();
//! # writeln!(f, "```output").unwrap();
//! # for n in 0..=10 {
//! # for i in 0..=n {
//! # write!(f, "{} ", choose(n, i)).unwrap();
//! # }
//! # writeln!(f, "").unwrap();
//! # }
//! # writeln!(f, "```").unwrap();
//! ```
//!
//! Gamma Plot:
//! ```rust
//! // Gamma plot
//! # use r2rs_base::traits::StatisticalSlice;
//! # use r2rs_nmath::func::gamma;
//! # use strafe_plot::prelude::*;
//! # use strafe_type::FloatConstraint;
//! # use std::fs::rename;
//! let mut plot = Plot::new();
//! plot.with_options(PlotOptions {
//! y_min: Some(-20.0),
//! y_max: Some(20.0),
//! title: "Γ(x)".to_string(),
//! x_axis_label: "x".to_string(),
//! y_axis_label: "gamma(x)".to_string(),
//! ..Default::default()
//! });
//!
//! // gamma has 1st order poles at 0, -1, -2, ...
//! for sections in [-3.0, -2.0, -1.0, 0.0, 4.0].windows(2) {
//! let left = sections[0];
//! let right = sections[1];
//!
//! let x = <[f64]>::sequence(left + 1e-4, right - 1e-4, 200);
//! let y = x
//! .iter()
//! .map(|x| gamma(x).unwrap().unwrap())
//! .collect::<Vec<_>>();
//!
//! plot.with_plottable(Line {
//! x,
//! y,
//! color: RED,
//! ..Default::default()
//! });
//! }
//!
//! plot.with_plottable(HorizontalLine {
//! y: 0.0,
//! color: BLUE,
//! size: 1,
//! dash: true,
//! ..Default::default()
//! })
//! .with_plottable(VerticalLine {
//! x: -2.0,
//! color: BLUE,
//! size: 1,
//! dash: true,
//! ..Default::default()
//! })
//! .with_plottable(VerticalLine {
//! x: -1.0,
//! color: BLUE,
//! size: 1,
//! dash: true,
//! ..Default::default()
//! })
//! .with_plottable(VerticalLine {
//! x: 0.0,
//! color: BLUE,
//! size: 1,
//! dash: true,
//! ..Default::default()
//! })
//! .plot(&SVGBackend::new("gamma.svg", (1024, 768)).into_drawing_area())
//! .unwrap();
//! # rename(
//! # format!("gamma.svg"),
//! # format!("src/func/betagam/doctest_out/gamma.svg"),
//! # )
//! # .unwrap();
//! ```
//!
//! Psigamma Plot:
//! ```rust
//! # use r2rs_base::traits::StatisticalSlice;
//! # use r2rs_nmath::func::{gamma, lgamma, psigamma};
//! # use strafe_plot::prelude::{*, full_palette::GREY_600};
//! # use strafe_type::FloatConstraint;
//! # use std::fs::rename;
//! let x = <[f64]>::sequence(0.1, 4.0, 201);
//!
//! let dx = x.windows(2).map(|xs| xs[1] - xs[0]).collect::<Vec<_>>();
//! let x_temp = x[0..201].to_vec();
//!
//! let y = x
//! .iter()
//! .map(|x| gamma(x).unwrap().unwrap())
//! .collect::<Vec<_>>();
//!
//! let root = SVGBackend::new("psigamma.svg", (1024, 768)).into_drawing_area();
//!
//! Plot::new()
//! .with_options(PlotOptions {
//! plot_right: 1.0 / 3.0,
//! plot_bottom: 0.5,
//! title: "gamma".to_string(),
//! x_axis_label: "x".to_string(),
//! y_axis_label: "y".to_string(),
//! ..Default::default()
//! })
//! .with_plottable(HorizontalLine {
//! y: 0.0,
//! color: GREY_600,
//! size: 1,
//! ..Default::default()
//! })
//! .with_plottable(Line {
//! x: x.clone(),
//! y,
//! color: RED,
//! ..Default::default()
//! })
//! .plot(&root)
//! .unwrap();
//!
//! let y = x
//! .iter()
//! .map(|x| lgamma(x).unwrap().unwrap())
//! .collect::<Vec<_>>();
//!
//! Plot::new()
//! .with_options(PlotOptions {
//! plot_left: 1.0 / 3.0,
//! plot_right: 2.0 / 3.0,
//! plot_bottom: 0.5,
//! title: "lgamma".to_string(),
//! x_axis_label: "x".to_string(),
//! y_axis_label: "y".to_string(),
//! ..Default::default()
//! })
//! .with_plottable(HorizontalLine {
//! y: 0.0,
//! color: GREY_600,
//! size: 1,
//! ..Default::default()
//! })
//! .with_plottable(Line {
//! x: x.clone(),
//! y: y.clone(),
//! color: RED,
//! ..Default::default()
//! })
//! .plot(&root)
//! .unwrap();
//!
//! let dy = y
//! .windows(2)
//! .zip(dx.iter())
//! .map(|(ys, dx)| (ys[1] - ys[0]) / dx)
//! .collect::<Vec<_>>();
//! let y = x
//! .iter()
//! .map(|x| psigamma(x, 0).unwrap().unwrap())
//! .collect::<Vec<_>>();
//!
//! Plot::new()
//! .with_options(PlotOptions {
//! plot_left: 2.0 / 3.0,
//! plot_right: 1.0,
//! plot_bottom: 0.5,
//! title: "digamma".to_string(),
//! x_axis_label: "x".to_string(),
//! y_axis_label: "y".to_string(),
//! ..Default::default()
//! })
//! .with_plottable(HorizontalLine {
//! y: 0.0,
//! color: GREY_600,
//! size: 1,
//! ..Default::default()
//! })
//! .with_plottable(Line {
//! x: x.clone(),
//! y: y.clone(),
//! color: RED,
//! ..Default::default()
//! })
//! .with_plottable(Line {
//! x: x_temp.clone(),
//! y: dy,
//! color: BLUE,
//! dash: true,
//! ..Default::default()
//! })
//! .plot(&root)
//! .unwrap();
//!
//! let dy = y
//! .windows(2)
//! .zip(dx.iter())
//! .map(|(ys, dx)| (ys[1] - ys[0]) / dx)
//! .collect::<Vec<_>>();
//! let y = x
//! .iter()
//! .map(|x| psigamma(x, 1).unwrap().unwrap())
//! .collect::<Vec<_>>();
//!
//! Plot::new()
//! .with_options(PlotOptions {
//! plot_right: 1.0 / 3.0,
//! plot_top: 0.5,
//! plot_bottom: 1.0,
//! title: "trigamma".to_string(),
//! x_axis_label: "x".to_string(),
//! y_axis_label: "y".to_string(),
//! ..Default::default()
//! })
//! .with_plottable(HorizontalLine {
//! y: 0.0,
//! color: GREY_600,
//! size: 1,
//! ..Default::default()
//! })
//! .with_plottable(Line {
//! x: x.clone(),
//! y: y.clone(),
//! color: RED,
//! ..Default::default()
//! })
//! .with_plottable(Line {
//! x: x_temp.clone(),
//! y: dy,
//! color: BLUE,
//! dash: true,
//! ..Default::default()
//! })
//! .plot(&root)
//! .unwrap();
//!
//! let dy = y
//! .windows(2)
//! .zip(dx.iter())
//! .map(|(ys, dx)| (ys[1] - ys[0]) / dx)
//! .collect::<Vec<_>>();
//! let y = x
//! .iter()
//! .map(|x| psigamma(x, 2).unwrap().unwrap())
//! .collect::<Vec<_>>();
//!
//! Plot::new()
//! .with_options(PlotOptions {
//! plot_left: 1.0 / 3.0,
//! plot_right: 2.0 / 3.0,
//! plot_top: 0.5,
//! plot_bottom: 1.0,
//! title: "psigamma(deriv=2)".to_string(),
//! x_axis_label: "x".to_string(),
//! y_axis_label: "y".to_string(),
//! ..Default::default()
//! })
//! .with_plottable(HorizontalLine {
//! y: 0.0,
//! color: GREY_600,
//! size: 1,
//! ..Default::default()
//! })
//! .with_plottable(Line {
//! x: x.clone(),
//! y: y.clone(),
//! color: RED,
//! ..Default::default()
//! })
//! .with_plottable(Line {
//! x: x_temp.clone(),
//! y: dy,
//! color: BLUE,
//! dash: true,
//! ..Default::default()
//! })
//! .plot(&root)
//! .unwrap();
//!
//! let dy = y
//! .windows(2)
//! .zip(dx.iter())
//! .map(|(ys, dx)| (ys[1] - ys[0]) / dx)
//! .collect::<Vec<_>>();
//! let y = x
//! .iter()
//! .map(|x| psigamma(x, 3).unwrap().unwrap())
//! .collect::<Vec<_>>();
//!
//! Plot::new()
//! .with_options(PlotOptions {
//! plot_left: 2.0 / 3.0,
//! plot_right: 1.0,
//! plot_top: 0.5,
//! plot_bottom: 1.0,
//! title: "psigamma(deriv=3)".to_string(),
//! x_axis_label: "x".to_string(),
//! y_axis_label: "y".to_string(),
//! ..Default::default()
//! })
//! .with_plottable(HorizontalLine {
//! y: 0.0,
//! color: GREY_600,
//! size: 1,
//! ..Default::default()
//! })
//! .with_plottable(Line {
//! x: x.clone(),
//! y,
//! color: RED,
//! ..Default::default()
//! })
//! .with_plottable(Line {
//! x: x_temp.clone(),
//! y: dy,
//! color: BLUE,
//! dash: true,
//! ..Default::default()
//! })
//! .plot(&root)
//! .unwrap();
//! # drop(root);
//! # rename(
//! # format!("psigamma.svg"),
//! # format!("src/func/betagam/doctest_out/psigamma.svg"),
//! # )
//! # .unwrap();
//! ```
//!
//! Binomial theorem for $n = \frac{1}{2}$
//!
//! $\sqrt{1+x} = (1+x)^{\frac{1}{2}} = \sum_{k=0}^\infty \text{choose}(\frac{1}{2}, k) * x^k$
//! ```rust
//! # use r2rs_nmath::func::choose;
//! # use strafe_type::FloatConstraint;
//! let k = 0..10; // 10 is sufficient for ~ 9 digit precision:
//! println!("{}", 1.25_f64.sqrt());
//! let sum = k
//! .map(|k| choose(1.0 / 2.0, k).unwrap() * 0.25_f64.powi(k))
//! .sum::<f64>();
//! println!("{sum}");
//! # use std::{fs::File, io::Write};
//! # let mut f = File::create("src/func/betagam/doctest_out/binomial_theorem.md").unwrap();
//! # writeln!(f, "```output").unwrap();
//! # writeln!(f, "{}", 1.25_f64.sqrt()).unwrap();
//! # writeln!(f, "{sum}").unwrap();
//! # writeln!(f, "```").unwrap();
//! ```
pub use ;