因此,正如标题所述,我目前正在做一个实验作业,以估计e^(sin(t))
的积分。我试图完成的所提供代码的一部分是for循环。
我到目前为止有什么
### Setting Up the Problem ###
a <- 0 ## Lower Bound of t.
b <-10 ## Upper Bound of t.
n <- 5 ## Number of Intervals.
dFdt <- function(t){exp(sin(t)) } ## What function we are trying to estimate the antiderivative?
UnitIntervalLength<-((b-a)/n) ## What is the length
of each interval in terms of a, b and n?
### Plot the Function
t <- seq(a,b,.01) ## Set the t-axis to visualize.
plot(t, dFdt(t), type="l") ## Plot the function dFdt at given interval 't', DO NOT FORGET TYPE='L'.
### Use R built-in function 'for' to start the recursive evaluation of the dfdt at either left end, right end or
### midpoint depends on the method you are using.
Sum <- 0 ## Start with a sum of zero.
for(i in 1:n){
t0 <-a+(i-1)*UnitIntervalLength ## t0 is the left end of the i-th interval
t1 <-t0+i ## t1 is the right end of the i-th interval
Eval_i <- dFdt(t) ## Evaluate function at either left end, right end or midpoint.
Area_i =UnitIntervalLength*t ## Area of the current box i, which is calculated as length*width
## Will Discuss the Following Blank in Lab
Sum <-1:n ## Add this value to previous
sum to keep track of the current sum.
## Here is the Plot of Each Box (No Need to Change the Following)
segments(x0=t0,x1=t1,y0=Eval_i)
segments(y0=0,y1=Eval_i,x0=t1)
polygon(c(t0,t1,t1,t0),c(0,0,Eval_i,Eval_i),col=i,density=45)
}
### Display the Final result on the Title of the Plot.
title(main=paste("The Integral is Approximately ",round(Sum,3), sep=""))
我尝试过的事情
我已经填写了所有部分并设置了方程式,但是我认为问题出在我的t1和我的Eval_i。我对t1的想法是,第i个间隔需要设置为+1到t0,这是每个间隔的左边。对于Eval_i,我一直认为这只是我要评估的功能。
所以我想知道我的断开连接是否会更快地发生,或者这两个变量是否是我唯一的问题。
修改 经过大量的尝试后,我发现了一个错误的解决方案。我在for循环中对不同变量的定义涉及几个问题。
t0 <-a+(i-1)*UnitIntervalLength
t1 <-a+i*UnitIntervalLength
Eval_i <- ((dFdt(t0)+dFdt(t1))/2)
Area_i =dFdt(t)*(t1-t0)
Sum<- Area_i+Sum