-
Notifications
You must be signed in to change notification settings - Fork 0
/
Chapter_25.Rmd
1311 lines (989 loc) · 21.7 KB
/
Chapter_25.Rmd
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Chapter 25"
author: "Julin Maloof"
date: "2023-10-04"
output:
html_document:
keep_md: yes
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r}
library(Rcpp)
library(tidyverse)
```
# 25.2 Getting STarted with C++
use cppFunction() to write a C++ function in R:
```{r}
cppFunction('int add(int x, int y, int z) {
int sum = x + y + z;
return sum;
}')
# add works like a regular R function
add
#> function (x, y, z)
#> .Call(<pointer: 0x107536a00>, x, y, z)
add(1, 2, 3)
#> [1] 6
```
## 25.2.1 No inputs, scalara output
```{r}
#R
one <- function() 1L
one()
one
#Cpp
cppFunction('int one() {
return 1;
}')
one()
one
```
## 25.2.2 Scalar input, scalar output
```{r}
signR <- function(x) {
if (x > 0) {
1
} else if (x == 0) {
0
} else {
-1
}
}
cppFunction('int signC(int x) {
if (x > 0) {
return 1;
} else if (x == 0) {
return 0;
} else {
return -1;
}
}')
```
## 25.2.3 Vector inpur, scalar output
```{r}
sumR <- function(x) {
total <- 0
for (i in seq_along(x)) {
total <- total + x[i]
}
total
}
cppFunction('double sumC(NumericVector x) {
int n = x.size();
double total = 0;
for(int i = 0; i < n; ++i) {
total += x[i];
}
return total;
}')
```
```{r}
x <- rnorm(10e6)
bench::mark(sumR(x),
sum(x),
sumC(x))
```
## 25.2.5 Vector input, Vector output
```{r}
pdistR <- function(x, ys) {
sqrt((x - ys) ^ 2)
}
cppFunction('NumericVector pdistC(double x, NumericVector ys) {
int n = ys.size();
NumericVector out(n);
for(int i = 0; i < n; ++i) {
out[i] = sqrt(pow(ys[i] - x, 2.0));
}
return out;
}')
y <- runif(1e6)
bench::mark(
pdistR(0.5, y),
pdistC(0.5, y)
)[1:6]
#> # A tibble: 2 x 6
#> expression min median `itr/sec` mem_alloc `gc/sec`
#> <bch:expr> <bch:tm> <bch:tm> <dbl> <bch:byt> <dbl>
#> 1 pdistR(0.5, y) 6.31ms 6.75ms 145. 7.63MB 72.4
#> 2 pdistC(0.5, y) 2.31ms 2.77ms 380. 7.63MB 192.
```
## 25.2.6 Exercises
### 1 With the basics of C++ in hand, it’s now a great time to practice by reading and writing some simple C++ functions. For each of the following functions, read the code and figure out what the corresponding base R function is. You might not understand every part of the code yet, but you should be able to figure out the basics of what the function does.
* f1: mean()
* f2: cumsum()
* f3: any()
* f4: ???
* f5: pmin()
```{Rcpp}
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
double f1(NumericVector x) {
int n = x.size();
double y = 0;
for(int i = 0; i < n; ++i) {
y += x[i] / n;
}
return y;
}
NumericVector f2(NumericVector x) {
int n = x.size();
NumericVector out(n);
out[0] = x[0];
for(int i = 1; i < n; ++i) {
out[i] = out[i - 1] + x[i];
}
return out;
}
bool f3(LogicalVector x) {
int n = x.size();
for(int i = 0; i < n; ++i) {
if (x[i]) return true;
}
return false;
}
int f4(Function pred, List x) {
int n = x.size();
for(int i = 0; i < n; ++i) {
LogicalVector res = pred(x[i]);
if (res[0]) return i + 1;
}
return 0;
}
NumericVector f5(NumericVector x, NumericVector y) {
int n = std::max(x.size(), y.size());
NumericVector x1 = rep_len(x, n);
NumericVector y1 = rep_len(y, n);
NumericVector out(n);
for (int i = 0; i < n; ++i) {
out[i] = std::min(x1[i], y1[i]);
}
return out;
}
```
### To practice your function writing skills, convert the following functions into C++. For now, assume the inputs have no missing values.
all().
cumprod(), cummin(), cummax().
diff(). Start by assuming lag 1, and then generalise for lag n.
range().
var(). Read about the approaches you can take on Wikipedia. Whenever implementing a numerical algorithm, it’s always good to check what is already known about the problem.
#### all
```{Rcpp}
# include <Rcpp.h>
using namespace Rcpp;
//[[Rcpp::export]]
bool allC(LogicalVector x) {
int n = x.size();
for (int i = 0; i < n; ++i) {
if(!x[i]) return false;
}
return true;
}
```
```{r}
all(c(T,T,T))
all(c(T,T,F,T))
allC(c(T,T,T))
allC(c(T,T,F,T))
```
#### cumX
```{Rcpp}
# include <Rcpp.h>
using namespace Rcpp;
//[[Rcpp::export]]
NumericVector cumprodC(NumericVector x) {
int n = x.size();
NumericVector res(n);
res[0] = x[0];
for(int i=1; i < n; ++i) {
res[i] = x[i]*res[i-1];
}
return res;
}
//[[Rcpp::export]]
NumericVector cumminC(NumericVector x) {
int n = x.size();
NumericVector res(n);
res[0] = x[0];
for(int i=1; i < n; ++i) {
if (x[i] < res[i-1])
res[i] = x[i];
else
res[i] = res[i-1];
}
return res;
}
//[[Rcpp::export]]
NumericVector cummaxC(NumericVector x) {
int n = x.size();
NumericVector res(n);
res[0] = x[0];
for(int i=1; i < n; ++i) {
if (x[i] > res[i-1])
res[i] = x[i];
else
res[i] = res[i-1];
}
return res;
}
```
```{r}
cumprod(2:10)
cumprodC(2:10)
cummin(c(3:1, 2:0, 4:2))
cumminC(c(3:1, 2:0, 4:2))
cummax(c(3:1, 2:0, 4:2))
cummaxC(c(3:1, 2:0, 4:2))
```
### diff
```{Rcpp}
# include <Rcpp.h>
using namespace Rcpp;
//[[Rcpp::export]]
NumericVector diffC(NumericVector x, int lag = 1) {
int n = x.size();
NumericVector res(n-lag);
for(int i = lag; i < n; ++i) {
res[i-lag] = x[i] - x[i-lag];
}
return res;
}
```
```{r}
diff((1:10)^2)
diffC((1:10)^2)
diff((1:10)^2, 2)
diffC((1:10)^2, 2)
```
#### range
```{Rcpp}
# include <Rcpp.h>
using namespace Rcpp;
//[[Rcpp::export]]
NumericVector rangeC(NumericVector x){
int n = x.size();
NumericVector result(2);
result[0] = result[1] = x[0];
for(int i = 1; i < n; ++i){
result[0] = std::min(result[0], x[i]);
result[1] = std::max(result[1], x[i]);
}
return(result);
}
```
```{r}
x <- sample(1:20)
x
range(x)
rangeC(x)
```
#### var
Okay wikipedia says that some pitfalls (e.g. cancellation) can be avoided by shifting the numbers to be centered around their mean, (or even anything in teh range) so I will try that. There are more exotic algorithms but this at least seems simple.
```{Rcpp}
# include <Rcpp.h>
using namespace Rcpp;
//[[Rcpp::export]]
double varC(NumericVector x){
int n = x.size();
double K = x[0];
double sumx = 0;
double sumsqx = 0;
for(int i = 0; i < n; ++i) {
sumx += (x[i] - K);
sumsqx += pow(x[i] -K, 2);
}
double var = (sumsqx - pow(sumx, 2)/n) / (n-1);
return(var);
}
```
```{r}
x <- rnorm(100)
var(x)
varC(x)
```
# 25.3 Other Classes
## 23.3.1 Lists and Dataframes
A bunch of other classes. The most important are Lists and DataFrames. These are often most useful for output, since they can contain arbitraty classes on input. But if the structure is known it can be used as input. For example, lm
Function to extract mean percentage error
```{Rcpp}
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
double mpe(List mod) {
if (!mod.inherits("lm")) stop("Input must be a linear model");
NumericVector resid = as<NumericVector>(mod["residuals"]);
NumericVector fitted = as<NumericVector>(mod["fitted.values"]);
int n = resid.size();
double err = 0;
for(int i = 0; i < n; ++i) {
err += resid[i] / (fitted[i] + resid[i]);
}
return err / n;
}
```
```{r}
mod <- lm(mpg ~ wt, data = mtcars)
mpe(mod)
#> [1] -0.0154
```
## 25.3.2 Functions
Can pass an R function to C++ so that it can be called from your C++ code. Because we don't know what it will return, the return class is "RObject"
```{Rcpp}
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
RObject callWithOne(Function f) {
return f(1);
}
```
```{r}
callWithOne(function(x) x + 1)
#> [1] 2
callWithOne(paste)
#> [1] "1"
```
If you need to pass names arguments to an R function from C++, the syntax is `f(_["x"] = "y", _["value"] = 1);`
## 25.3.4 Attributes
See below for setting names and attributes
```{Rcpp}
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector attribs() {
NumericVector out = NumericVector::create(1, 2, 3);
out.names() = CharacterVector::create("a", "b", "c");
out.attr("my-attr") = "my-value";
out.attr("class") = "my-class";
return out;
}
```
But what if you don't use ::create?
```{Rcpp}
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector attribs2(NumericVector x) {
x.names() = CharacterVector::create("a", "b", "c");
x.attr("my-attr") = "my-value";
x.attr("class") = "my-class";
return x;
}
```
```{r}
attribs2(4:6)
```
works
# 25.4 Missing Values
Need to know how missing values work in scalars and vectors
## 25.4.1 Scalars
```{Rcpp}
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
List scalar_missings() {
int int_s = NA_INTEGER;
String chr_s = NA_STRING;
bool lgl_s = NA_LOGICAL;
double num_s = NA_REAL;
return List::create(int_s, chr_s, lgl_s, num_s);
}
```
```{r}
scalar_missings()
```
Whoa, look out for the boolean...
Other wierdness
### 25.4.1.1 Integers:
C++ stores an NA as the smallest integer, so if you do an operation on it, then the value can change.
```{r}
evalCpp('NA_INTEGER + 1')
```
**yikes**
Solution: use an integer vector of length 1 or be very careful!
### 25.4.1.2 Doubles
somewhat better:
```{r}
evalCpp("NAN == 1")
#> [1] FALSE
evalCpp("NAN < 1")
#> [1] FALSE
evalCpp("NAN > 1")
#> [1] FALSE
evalCpp("NAN == NAN")
#> [1] FALSE
evalCpp("NAN + 1")
```
However...
```{r}
evalCpp("NAN && TRUE")
#> [1] TRUE
evalCpp("NAN || FALSE")
#> [1] TRUE
```
But math is OK
```{r}
evalCpp("NAN + 1")
#> [1] NaN
evalCpp("NAN - 1")
#> [1] NaN
evalCpp("NAN / 1")
#> [1] NaN
evalCpp("NAN * 1")
#> [1] NaN
```
## 25.4.2 Strings
OK
## 25.4.3 Boolean
C++ only has true and false, no NA. `int` however can have true, false, or NA
## 25.4.4 Vectors
With vectors, you need to use a missing value specific to the type of vector, NA_REAL, NA_INTEGER, NA_LOGICAL, NA_STRING:
```{Rcpp}
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
List missing_sampler() {
return List::create(
NumericVector::create(NA_REAL),
IntegerVector::create(NA_INTEGER),
LogicalVector::create(NA_LOGICAL),
CharacterVector::create(NA_STRING)
);
}
```
```{r}
str(missing_sampler())
```
## 25.4.5 Exercises
### 1 Rewrite any of the functions from the first exercise of Section 25.2.6 to deal with missing values. If na.rm is true, ignore the missing values. If na.rm is false, return a missing value if the input contains any missing values. Some good functions to practice with are min(), max(), range(), mean(), and var().
```{Rcpp}
# include <Rcpp.h>
using namespace Rcpp;
//[[Rcpp::export]]
double minC(NumericVector x, bool na_rm = false) {
int n = x.size();
double result=x[0];
for(int i=0; i < n; ++i) {
if (std::isnan(x[i])) {
if (na_rm) continue;
else return(NA_REAL);
}
result = std::min(result, x[i]);
}
return(result);
}
```
```{r}
x <- rnorm(100)
min(x)
minC(x)
minC(x, TRUE)
```
```{r}
x[50] <- NA
min(x)
min(x, na.rm = TRUE)
minC(x)
minC(x, na_rm = TRUE)
```
#### Range
```{Rcpp}
# include <Rcpp.h>
using namespace Rcpp;
//[[Rcpp::export]]
NumericVector rangeC(NumericVector x, bool na_rm = false){
int n = x.size();
NumericVector result(2);
int start = 0;
if(isnan(x[0])) {
if(na_rm) ++start; // Skip the NA in position 0
else return(NA_REAL);
}
result[0] = result[1] = x[start];
++start;
for(int i = start; i < n; ++i){
if(isnan(x[i])) {
if(na_rm) continue;
else return(NumericVector::create(NA_REAL, NA_REAL));
}
result[0] = std::min(result[0], x[i]);
result[1] = std::max(result[1], x[i]);
}
return(result);
}
```
```{r}
x <- rnorm(100)
range(x)
rangeC(x)
x[50] <- NA
range(x)
rangeC(x)
range(x, na.rm=TRUE)
rangeC(x, na_rm = TRUE)
```
#### mean
we could either run through the vector twice, first to detect/discard NAs and then compute the mean, or we could run through it once, keeping a separate counter. Second way seems better.
```{Rcpp}
# include <Rcpp.h>
using namespace Rcpp;
//[[Rcpp::export]]
double meanC(NumericVector x, bool na_rm = false){
int n = x.length();
int count = 0;
double sum = 0;
for(int i = 0; i < n; ++i) {
if(isnan(x[i])) {
if(na_rm) continue; // Skip the NA in position 0
else return(NA_REAL);
}
sum += x[i];
++count;
}
return(sum/count);
}
```
```{r}
x <- rnorm(100)
mean(x)
meanC(x)
x[30] <- NaN
mean(x)
meanC(x)
mean(x, na.rm = TRUE)
meanC(x, na_rm = TRUE)
```
Alternate, using na_omit
```{Rcpp}
# include <Rcpp.h>
using namespace Rcpp;
//[[Rcpp::export]]
double meanC2(NumericVector x, bool na_rm = false){
if(is_true(any(is_na(x)))) {
if(na_rm) x = na_omit(x);
else return(NA_REAL);
}
int n = x.length();
double sum = 0;
for(int i = 0; i < n; ++i) {
sum += x[i];
}
return(sum/n);
}
```
```{r}
x <- rnorm(100)
mean(x)
meanC2(x)
x[30] <- NaN
mean(x)
meanC2(x)
mean(x, na.rm = TRUE)
meanC2(x, na_rm = TRUE)
```
### 2. Rewrite cumsum() and diff() so they can handle missing values. Note that these functions have slightly more complicated behaviour.
#### cumsum
From `cumsum()` help file: _An NA value in x causes the corresponding and following elements of the return value to be NA, as does integer overflow in cumsum (with a warning)._
```{Rcpp}
# include <Rcpp.h>
using namespace Rcpp;
//[[Rcpp::export]]
NumericVector cumsumC(NumericVector x) {
bool na_found = false;
int n = x.size();
NumericVector out(n);
out[0] = x[0];
for(int i = 1; i < n; ++i) {
if(na_found) {
out[i] = NA_REAL;
continue;
}
if(NumericVector::is_na(x[i])) {
na_found = true;
out[i] = NA_REAL;
continue;
}
out[i] = out[i - 1] + x[i];
}
return out;
}
```
```{r}
x <- rnorm(20, 10)
x[15] <- NA
cumsum(x)
cumsumC(x)
```
### diff
```{Rcpp}
# include <Rcpp.h>
using namespace Rcpp;
//[[Rcpp::export]]
NumericVector test() {
NumericVector v = {2,4,6,8,10};
return(v[NumericVector::create(2,4)]);
}
```
```{r}
test()
```
```{Rcpp}
# include <Rcpp.h>
using namespace Rcpp;
//[[Rcpp::export]]
NumericVector diffC(NumericVector x, int lag = 1) {
int n = x.size();
NumericVector res(n-lag);
for(int i = lag; i < n; ++i) {
if(NumericVector::is_na(x[i]) | NumericVector::is_na(x[i-lag])) {
res[i-lag] = NA_REAL;
} else {
res[i-lag] = x[i] - x[i-lag];
}
}
return res;
}
```
```{r}
x <- rnorm(20, 10)
x[15] <- NA
diff(x)
diffC(x)
```
# 25.5 Standard Template Library
## 25.5.1 Using Iterators
* Advance with `++`
* dereference with `*`
* compare with `==`
For example:
```{Rcpp}
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
double sum3(NumericVector x) {
double total = 0;
NumericVector::iterator it;
for(it = x.begin(); it != x.end(); ++it) {
Rcout << *it << " ";
total += *it;
}
return total;
}
```
```{r}
sum3(10:1)
```
Or using accumulate
```{Rcpp}
#include <numeric>
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
double sum5(NumericVector x) {
return std::accumulate(x.begin(), x.end(), 0.0);
}
```
```{r}
sum5(10:1)
```
## 25.5.2 Algorithims.
The algorithm header provides a large number of iterator functions. Consider:
```{Rcpp}
#include <Rcpp.h>
#include <algorithm>
using namespace Rcpp;
// [[Rcpp::export]]
IntegerVector findInterval2(NumericVector x, NumericVector breaks) {
IntegerVector out(x.size());
NumericVector::iterator it, pos;
IntegerVector::iterator out_it;
for(it = x.begin(), out_it = out.begin(); it != x.end();
++it, ++out_it) {
pos = std::upper_bound(breaks.begin(), breaks.end(), *it);
*out_it = std::distance(breaks.begin(), pos);
Rcout << *pos << " " << *out_it << std::endl;
}
return out;
}
```
```{r}
findInterval2(1:10, c(0,3,6,10))
```
## 25.5.3 Data structures.
There are a bunch of them. Perhaps most useful are `vector`, `unordered_set`, and `unordered_map`
## 25.5.4 Vectors
can access with vect[]. Can add to the end with vect.push_back()
```{Rcpp}
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
List rleC(NumericVector x) {
std::vector<int> lengths;
std::vector<double> values;
// Initialise first value
int i = 0;
double prev = x[0];
values.push_back(prev);
lengths.push_back(1);
NumericVector::iterator it;
for(it = x.begin() + 1; it != x.end(); ++it) {
if (prev == *it) {
lengths[i]++;
} else {
values.push_back(*it);
lengths.push_back(1);
i++;
prev = *it;
}
}
return List::create(
_["lengths"] = lengths,
_["values"] = values
);
}
```
## set
## map
a map has a key and value pair
```{Rcpp}
#include <Rcpp.h>
#include <algorithm>
using namespace Rcpp;
// [[Rcpp::export]]
std::map<double, int> tableC(NumericVector x) {
std::map<double, int> counts;
int n = x.size();
for (int i = 0; i < n; i++) {
counts[x[i]]++;
}