if(.Platform$OS.type=="windows") invisible(Sys.setlocale("LC_CTYPE","English_United States.utf8"))
# Run from the script folder; explicit for-loops define sequential arithmetic.
sequential <- function(v){ s <- 0;for(x in v)s <- s+x;s }
kahan <- function(v){s <- 0;c <- 0;for(x in v){ y <- x-c;t <- s+y;c <- (t-s)-y;s <- t };s}
neumaier <- function(v){s <- 0;c <- 0;for(x in v){t <- s+x;c <- c+if(abs(s)>=abs(x))(s-t)+x else (x-t)+s;s <- t};s+c}
results <- numeric()
for(p in c(2,4)) for(n in c(2,4,10,100)){
 x <- (0:n)/n;y <- x^p
 results[paste0("x",p,"_trapezoid_",n)] <- (sum(y[2:n])+(y[1]+y[n+1])/2)/n
 results[paste0("x",p,"_simpson_",n)] <- (y[1]+y[n+1]+sum(ifelse((1:(n-1))%%2==1,4,2)*y[2:n]))/(3*n)
}
perms <- list(c(1e16,1,-1e16),c(1e16,-1e16,1),c(1,1e16,-1e16),c(1,-1e16,1e16),c(-1e16,1e16,1),c(-1e16,1,1e16))
for(i in seq_along(perms)) for(method in c("sequential","kahan","neumaier")) results[paste0("sum_",i-1,"_",method)] <- get(method)(perms[[i]])
for(label in c("complete","missing")){
 file <- if(label=="complete") "power-2006-12-17.csv" else "power-2007-04-28.csv"
 rows <- read.csv(paste0("math10-sources/",file),colClasses="character",check.names=FALSE,na.strings=c("?","NA",""))
 kw <- as.numeric(rows$Global_active_power);w <- round(kw[!is.na(kw)]*1000)
 results[paste0(label,"_known")] <- length(w);results[paste0(label,"_missing")] <- nrow(rows)-length(w)
 results[paste0(label,"_integer_w_sum")] <- sum(w);results[paste0(label,"_reference_kwh")] <- sum(w)/60000
 for(d in 0:3){step <- 10^(3-d);results[paste0(label,"_round",d,"_kwh")] <- sum(floor(w/step+.5)*step)/60000}
 if(label=="complete"){
   sums <- vapply(split(w,rep(1:24,each=60)),sum,numeric(1))
   results["rounded_hour_groups_kwh"] <- sum(floor((sums+300)/600))/100
   results["first3_energy_kwh"] <- sum(w[1:3])/60000
 }
}
for(h in c(.01,.1,1)){
 results[paste0("exp_forward_h",format(h,trim=TRUE))] <- (exp(1+h)-exp(1))/h
 results[paste0("exp_central_h",format(h,trim=TRUE))] <- (exp(1+h)-exp(1-h))/(2*h)
}
write.csv(data.frame(quantity=names(results),value=unname(results)),"math12-r-results.csv",row.names=FALSE)
cat("MATH-12:",length(results),"quantities\n")
