N_simulations = 1000; % 模拟次数 RV_simulations = zeros(N+1, N_simulations); % 初始化模拟结果 p=0.2; for j = 1:N_simulations X_MC = zeros(1,N+1); % 初始化样本路径 X_MC(1) = 0; for i = 1:N if X_MC(i) <= 0.2 &rand() < p X_MC(i+1) = X_MC(i); else X_MC(i+1) = X_MC(i) + theta*(mu - X_MC(i))*dt + sigma*sqrt(dt)*randn; end end RV_MC = zeros(1,N+1); for i = 2:N+1 if isreal(X_MC(i-1)) && X_MC(i-1) == 0 X_MC(i-1) = 1e-10; end RV_MC(i) = RV_MC(i-1) + (log(X_MC(i)/X_MC(i-1)))^2; end RV_simulations(:,j) = RV_MC; end alpha_MC = 0.05; % 蒙特卡罗置信水平 z_alpha_MC = norminv(1-alpha_MC/2); % 蒙特卡罗分位点 RV1_simulations=real(RV_simulations); ub_MC = quantile(RV_simulations'+1e-10, 1-alpha_MC/2)'; lb_MC = quantile(RV_simulations', alpha_MC/2)'; hold on; plot(t,ub_MC,':'); plot(t,lb_MC,':');置信上限出现inf怎么修改代码
时间: 2024-03-23 08:43:17 浏览: 51
在计算置信上限时,如果出现inf,可以考虑将分母加上一个很小的数epsilon,防止分母为0的情况发生。在这段代码中,我们可以将计算RV_MC时分母加上epsilon,如下所示:
```matlab
N_simulations = 1000; % 模拟次数
RV_simulations = zeros(N+1, N_simulations); % 初始化模拟结果
p=0.2;
epsilon = 1e-10; % 设置一个很小的数,防止分母为0
for j = 1:N_simulations
X_MC = zeros(1,N+1); % 初始化样本路径
X_MC(1) = 0;
for i = 1:N
if X_MC(i) <= 0.2 & rand() < p
X_MC(i+1) = X_MC(i);
else
X_MC(i+1) = X_MC(i) + theta*(mu - X_MC(i))*dt + sigma*sqrt(dt)*randn;
end
end
RV_MC = zeros(1,N+1);
for i = 2:N+1
if isreal(X_MC(i-1)) && X_MC(i-1) == 0
X_MC(i-1) = epsilon; % 如果分母为0,将分母赋值为epsilon
end
RV_MC(i) = RV_MC(i-1) + (log(X_MC(i)/X_MC(i-1)))^2 / (X_MC(i-1) + epsilon); % 将分母加上epsilon
end
RV_simulations(:,j) = RV_MC;
end
alpha_MC = 0.05; % 蒙特卡罗置信水平
z_alpha_MC = norminv(1-alpha_MC/2); % 蒙特卡罗分位点
RV1_simulations=real(RV_simulations);
ub_MC = quantile(RV_simulations'+epsilon, 1-alpha_MC/2)';
lb_MC = quantile(RV_simulations', alpha_MC/2)';
hold on;
plot(t,ub_MC,':');
plot(t,lb_MC,':');
```
在这个代码中,我们在计算RV_MC时,将分母加上了epsilon,即将`(X_MC(i-1))^2`改为了`(X_MC(i-1) + epsilon)^2`。同样,在计算置信上限时,也需要将epsilon加上。这样可以避免分母为0的情况发生,进而避免出现inf。
阅读全文