# Base R. Source intentionally ASCII; the data-folder name is Unicode-escaped.
if(.Platform$OS.type=="windows") invisible(Sys.setlocale("LC_CTYPE","English_United States.utf8"))
args <- commandArgs(trailingOnly=FALSE)
filearg <- grep("^--file=",args,value=TRUE)
root <- if(length(filearg)) dirname(normalizePath(sub("^--file=","",filearg[1]))) else getwd()
h <- read.csv(file.path(root,"\uc2e4\uc81c\ub370\uc774\ud130","korea-housing.csv"))
value_at <- function(q) h$nominal[h$quarter==q]
initial <- value_at("2020-Q4"); target <- value_at("2024-Q4")
iterate <- function(lambda,steps=20) {
  path <- numeric(steps+1); path[1] <- initial
  for(i in seq_len(steps)) path[i+1] <- (1-lambda)*path[i]+lambda*target
  formula <- target+(1-lambda)^(0:steps)*(initial-target)
  stopifnot(max(abs(path-formula))<1e-9)
  path
}
path <- iterate(.5)
a <- value_at("2024-Q2"); b <- value_at("2024-Q3"); threshold <- 142.3
theta <- (threshold-a)/(b-a)
lo <- 0; hi <- 1
for(i in 1:20) {
  mid <- (lo+hi)/2
  if(a+(b-a)*mid<threshold) lo <- mid else hi <- mid
}
stopifnot(lo<=theta,theta<=hi)
# Integer fractions give the strict decimal-boundary checks independently.
minimum_n <- function(numerator,denominator) floor(denominator/numerator)+1
inside_reciprocal <- function(N,numerator,denominator) denominator<numerator*N
v <- c(observations=nrow(h),first_index=h$nominal[1],last_index=target,
  initial_anchor=initial,initial_distance=target-initial,
  step1=path[2],step2=path[3],step3=path[4],
  first_strict_tenth=which(abs(path-target)<.1)[1]-1,
  error6=abs(path[7]-target),error7=abs(path[8]-target),
  minimum_N_tenth=minimum_n(1,10),minimum_N_hundredth=minimum_n(1,100),
  N10_passes_tenth=inside_reciprocal(10,1,10),N11_passes_tenth=inside_reciprocal(11,1,10),
  delta_tenth_passes=3*1<=3,delta_two_tenths_passes=3*2<=3,
  counterexample_x=2.15,counterexample_output_distance=.45,
  interpolation_theta=theta,bisection_low=lo,bisection_high=hi,bisection_width=hi-lo)
for(lambda in c(0,.5,1,1.5,2,2.1)) v[paste0("lambda_",lambda,"_step20")] <- tail(iterate(lambda),1)
write.csv(data.frame(metric=names(v),value=as.numeric(v)),file.path(root,"math07-r-results.csv"),row.names=FALSE)
print(v)
