Chapter 4 Fibonacci Sequences Three

R

fib3_r <- function(n) {
    first <- 0
    second <- 1
    third <- 0
    for (i in seq_len(n)) {
        third <- first + second
        first <- second
        second <- third
    }
    first
}

C++

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
double fib3_cpp(int n) {
    double first = 0;
    double second = 1;
    double third = 0;
    for (int i=0; i<n; i++) {
        third = first + second;
        first = second;
        second = third;
    }
    return first;
}

Rust

pub fn fib3_rs(a : i32) -> f64{
    let mut first  = 0.0;
    let mut second = 1.0;
    let mut third  = 0.0;
    for _ in 0..a {
        third = first + second;
        first = second;
        second = third;
    }
    first
}

R script

library(Rcpp)
library(rustinr)
library(microbenchmark)

fib3_r <- function(n) {
    first <- 0
    second <- 1
    third <- 0
    for (i in seq_len(n)) {
        third <- first + second
        first <- second
        second <- third
    }
    first
}

sourceCpp(code = '
#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
NumericVector fib3_cpp(int n) {
    double first = 0;
    double second = 1;
    double third = 0;
    for (int i=0; i<n; i++) {
        third = first + second;
        first = second;
        second = third;
    }
    return Rcpp::wrap(first);
}
')

rust(code = '
// #[rustr_export]
pub fn fib3_rs(a : i32) -> f64{
    let mut first  = 0.0;
    let mut second = 1.0;
    let mut third  = 0.0;
    for _ in 0..a {
        third = first + second;
        first = second;
        second = third;
    }
    first
}
')

microbenchmark(fib3_r(2000L),fib3_cpp(2000L),fib3_rs(2000L))
#> Unit: microseconds
#>             expr    min     lq    mean median     uq    max neval
#>    fib3_r(2000L) 720.60 853.57 1011.61 942.84 987.98 2117.3   100
#>  fib3_cpp(2000L)   7.58   8.51   10.23   9.09  10.43   49.7   100
#>   fib3_rs(2000L)   3.04   3.53    5.69   4.82   5.86   31.3   100