R语言编程:
#0到1 sin(x)/x积分(投点法)
n=1000
x=runif(n);y=runif(n)
g<-function(x) sin(x)/x
length(x[y<=g(x)])/n #sum(y<=g(x))/n
plot(x,y,pch=16,col=c((y<=g(x))+1))
lines(sort(x),g(sort(x)),col="blue",lwd=2)
或直接套用函数(都可以用)
integrate(g,0,1)
> x=c(1,3,6,9,2)
> m=c(TRUE,FALSE,TRUE,FALSE,TRUE)
> x[m]
[1] 1 6 2
> m
[1] TRUE FALSE TRUE FALSE TRUE
> c(m+1)
[1] 2 1 2 1 2
其他参数见网址
> x<-c(97,93,85,74,32,100,99,67)
> sort(x)
[1] 32 67 74 85 93 97 99 100
其他关于排序的见网址
> n=1000
> x=runif(n);y=runif(n)
> g<-function(x) sin(x)/x
> length(x[y<=g(x)])/n #sum(y<=g(x))/n
[1] 0.945
> plot(x,y,pch=16,col=c((y<=g(x))+1))
> lines(sort(x),g(sort(x)),col="blue",lwd=2)
R语言编程:
#0到1 (cos50x+sin20x)^2积分(投点法)
n=10000
x=runif(n);y=runif(n,0,4)
g<-function(x) {(cos(50*x)+sin(20*x))^2}
p<-length(x[y<=g(x)])/n;i<-4*p;i
> n=10000
> x=runif(n);y=runif(n,0,4)
> g<-function(x) {(cos(50*x)+sin(20*x))^2}
> p<-length(x[y<=g(x)])/n;i<-4*p;i
[1] 0.9544
R语言编程:
#-2到2 e^(x+x^2)积分(平均值法)
f1=function(n,a,b,f){
x=runif(n)
sum((b-a)*f(a+(b-a)*x))/length(z)
}
n=100000;a=-2;b=2
f=function(x) {\exp(x+x^2)}
f1(n.a,b,f)
#或(内置函数)
integrate(f,a,b)
> #-2到2 e^(x+x^2)积分(平均值法)
> f1=function(n,a,b,f){
+ x=runif(n)
+ sum((b-a)*f(a+(b-a)*x))/length(x)
+ }
> n=100000;a=-2;b=2
> f=function(x) {exp(x+x^2)}
> f1(n,a,b,f)
[1] 93.95082
> #或(内置函数)
> integrate(f,a,b)
93.16275 with absolute error < 0.00062
R语言编程
#0到1 0到1 e^(x+y)^2(平均值法)
x=runif(100000,0,1)
y=runif(100000,0,1)
f=function(x,y) exp((x+y)^2)
sum(1*1*f(x,y))/length(x)
> #0到1 0到1 e^(x+y)^2(平均值法)
> x=runif(100000,0,1)
> y=runif(100000,0,1)
> f=function(x,y) exp((x+y)^2)
> sum(1*1*f(x,y))/length(x)
[1] 4.88204
R语言编程:
#0到1 sqrt(1-x^2)
#(投点法)
n=100000
x=runif(n,0,1);y=runif(n,0,1)
g=function(x) sqrt(1-x^2)
1*1*length(x[y<=g(x)])/length(x)
#(平均值法)
n=10000
x=runif(n,0,1)
1*sum(sqrt(1-x^2))/length(x)
> #0到1 sqrt(1-x^2)
> #(投点法)
> n=100000
> x=runif(n,0,1);y=runif(n,0,1)
> g=function(x) sqrt(1-x^2)
> 1*1*length(x[y<=g(x)])/length(x)
[1] 0.7854
>
> #(平均值法)
> n=10000
> x=runif(n,0,1)
> 1*sum(sqrt(1-x^2))/length(x)
[1] 0.7814675
(1)
R语言编程:
#(1)
#0到1 e^(e^x)
f=function(x) exp(exp(x))
integrate(f,0,1)
#(2)
#0到∞ x(1+x^2)^-2
f=function(x) x*(1+x^2)^(-2)
integrate(f,0,Inf)
#(3)
#0到1 x*sinx
f=function(x) x*sin(x)
integrate(f,0,1)
#(4)
#0到1 sin(e^x)
f=function(x) sin(exp(x))
integrate(f,0,1)
> #(1)
> #0到1 e^(e^x)
> f=function(x) exp(exp(x))
> integrate(f,0,1)
6.316564 with absolute error < 7e-14
> #(2)
> #0到∞ x(1+x^2)^-2
> f=function(x) x*(1+x^2)^(-2)
> integrate(f,0,Inf)
0.5 with absolute error < 3.3e-09
> #(3)
> #0到1 x*sinx
> f=function(x) x*sin(x)
> integrate(f,0,1)
0.3011687 with absolute error < 3.3e-15
> #(4)
> #0到1 sin(e^x)
> f=function(x) sin(exp(x))
> integrate(f,0,1)
0.8749572 with absolute error < 9.7e-15