
## com48a of september 2024,
#  revisiting some Weierstrass Bernstein from sporteaching 2020,
#  some Bernstein polynomials to prove Weierstrass, stk4011 Ch 2

#  may play with different g(p), e.g. 1 + sin(10*pi*p) etc.,
#  to see how big the polynomials need to be in order to have
#  ok approximation; i then adjust the nval below 

#  may also play with the *nils repaired polynomials* of order n + 2;
#  these will go faster to the given g(p) function 

gg <- function(x)
{
sin(2*pi*x) + exp(1.234*(sin(sqrt(x))^3)) - exp(-4.321*(cos(x^2))^5)
}

# gg <- function(x)
# {1 + sin(8*pi*x)} 

curve(gg,0,1)

pval <- seq(0,1,by=0.001)
ggval <- 0*pval

for (j in 1:length(pval))
{
ggval[j] <- gg(pval[j])
}

## then the Bernstein polynomials: 

nval <- seq(10,100,by=10)
# nval <- seq(25,2000,by=25)
# for the oscillating sinus example, need bigger n 
Bnval <- 0*pval %*% t(nval) 
checkval <- 0*nval 

for (kk in 1:length(nval))
{
nn <- nval[kk]

jj <- 0:nn

Bn <- function(p)
{
hei <- gg(jj/nn)*dbinom(jj,nn,p)
sum(hei)
}

for (j in 1:length(pval))
{
Bnval[j,kk] <- Bn(pval[j])
}

checkval[kk] <- max(ggval-Bnval[ ,kk])
}

# making largesample_figure14.pdf : 

par(bty="l")
par(cex.lab=1.4142) 

matplot(pval,cbind(Bnval),type="l",
   ylim=c(min(ggval),max(ggval)), 
   xlab="p",ylab="g(p), with Bernstein polynomials",
   col=4,lty=2,lwd=2.5)

matlines(pval,ggval,type="l",col=1,lwd=4)

print( cbind(nval,checkval) ) 