[過去ログ] 高校数学の質問スレ(医者・東大卒専用) Part438 (1002レス)
上下前次1-新
このスレッドは過去ログ倉庫に格納されています。
次スレ検索 歴削→次スレ 栞削→次スレ 過去ログメニュー
850: 05/25(日)06:42 ID:P4nhnL8B(4/6) AAS
# If verbose flag is TRUE, plot the Beta distribution and annotate results
if (verbose) {
# Generate x values from 0 to 1 for plotting the density
x <- seq(0, 1, length.out = 1000)
# Compute Beta density values at x
y <- dbeta(x, alpha, beta)
# Color bars within the credible interval [lower, upper] as "lightcoral",
# others as light gray ("gray70")
col <- ifelse(x >= lower & x <= upper, "lightcoral", "gray70")
# Plot histogram-like vertical lines representing the Beta density
plot(x, y, type = "h", col = col, lwd = 2,
main = sprintf("Beta(%.2f, %.2f) Distribution\n[%s, %s] with %.0f%% Probability Mass",
alpha, beta, fractionStr(lower), fractionStr(upper), credMass * 100),
xlab = "x", ylab = "Density", bty = "n")
# Add vertical dashed line for the mean, colored skyblue
abline(v = mean, col = "skyblue", lwd = 1, lty = 2)
# Add vertical dashed line for the mode if defined, colored dark green
if (!is.na(mode)) {
abline(v = mode, col = "darkgreen", lwd = 1, lty = 2)
}
# Prepare legend labels for mean, mode (if exists), and credible interval
labels <- c(
paste0("Mean = ", round(mean, 3)),
if (!is.na(mode)) paste0("Mode = ", round(mode, 3)) else NULL,
paste0("95% Credible Interval [", fractionStr(lower), ", ", fractionStr(upper), "]")
)
# Corresponding colors for legend items
colors <- c(
"skyblue",
if (!is.na(mode)) "darkgreen" else NULL,
"lightcoral"
)
# Line types for legend items (dashed lines for mean and mode, none for credible interval)
ltys <- c(2, if (!is.na(mode)) 2 else NULL, NA)
# Plot characters for legend (none for lines, solid square for interval)
pchs <- c(NA, if (!is.na(mode)) NA else NULL, 15)
# Add legend at the top of the plot with no box, scaled text size
legend("top", legend = labels, col = colors, bty = "n", cex = 0.9,
lty = ltys, pch = pchs)
}
# Return a named vector of calculated parameters and statistics
c(alpha = alpha, beta = beta, mean = mean, mode = mode)
}
851: 05/25(日)06:51 ID:P4nhnL8B(5/6) AAS
今回スムーズに機能拡張できた理由は、以下のようにプロトタイプが非常に明快かつ健全だったことが大きな要因です。
✅ プロトタイプの良さが拡張性を支えた理由
1. 構造がシンプル
中心となる数式(pbeta(U, a, b) - pbeta(L, a, b) = credMass)が明確で、ロジックが一貫していました。
f(a) で b を a の関数として定義しており、探索空間を1次元に抑えていた点も効率的。
2. 関数分離と再利用が可能
f(a) や g(a) が関数として定義されていたので、視覚化やバリエーションの追加が簡単でした。
3. 出力が明確
c(a, b) と返す構造が明瞭で、追加情報(期待値・最頻値など)も素直に足せました。
4. 数値的安定性が良好
uniroot() による根の探索は数値計算としても信頼性が高く、実用的。
852: 05/25(日)10:38 ID:P4nhnL8B(6/6) AAS
HDI_discrete <- function(prob_data, credMass) {
x = prob_data[, 1]
p = prob_data[, 2]
n = length(x)
sp = sort(p, index.return = TRUE)
i = sp$ix[seq(n, 1, -1)]
ps = p[i]
xs = x[i]
cp = cumsum(ps)
ii = 1:n
j = ii[cp >= credMass]
j = j[1]
achieved_credMass = cp[j]
hdi_set = sort(xs[1:j])
v = list(credMass = achieved_credMass, set = hdi_set)
return(v)
}
853: 05/29(木)17:36 ID:WPcwJ6cn(1) AAS
"
サイコロを50回なげて4回1の目がでた。
1の目のでる確率は1/6である仮説が正しい確率を求めよ。
計算に必要なモデルは適宜設定してよい。
例:サイコロを投げる前のこの仮説が正しい確率は一様分布に従う。
a/(a+b)=p
a=p(a+b)
(1-p)a=pb
b=a*(1-p)/p
a=b*p/(1-p)
a/b=p/(1-p)
"
rm(list=ls())
p=1/6
n=50
y=4
pbinom(y,n,p)
dbinom(y,n,p)
fn <- function(prob){
sub <-function(alpha) pbetat(p,prob,c(1,(1-p)/p)*alpha,c(y,n-y))$post
optimize(sub,c(1,100))$objective
}
fn = Vectorize(fn)
fn(0.5)
prior.probs=runif(1e6)
post.probs=fn(prior.probs)
summary(post.probs)
HDInterval::hdi(post.probs)
source("plotpost.R")
plotpost(post.probs,col="lightcoral")
lines(density(post.probs))
854: 05/30(金)06:24 ID:zoAuXcvc(1/3) AAS
par(bty="l")
y = c(43, 24, 100, 35, 85)
yn = max(y)
n = length(y)
B = 200
like = numeric(B)
for(i in yn:B) { like[i] = 1 / (i^n) }
pmf = like / sum(like)
mean = sum((1:B) * pmf)
plot(pmf, main="Posterior PMF of N", xlab="N", ylab="Probability", type="h", col="blue")
plot(cumsum(pmf), main="Posterior CDF of N", xlab="N", ylab="Cumulative Probability", type="s", col="blue")
abline(h=0.95, lty=3)
c(lower=yn, mean=mean, upper=which(cumsum(pmf) > 0.95)[1])
sd = sqrt(sum(((1:B) - mean)^2 * pmf))
prob_N_gt_150 = sum(pmf[151:B])
cat("Posterior Mean:", mean, "\n")
cat("Posterior Standard Deviation:", sd, "\n")
cat("P(N > 150):", prob_N_gt_150, "\n")
855: 05/30(金)19:44 ID:zoAuXcvc(2/3) AAS
(* pbetat関数の定義 *)
pbetat[p0_, prob_, ab_, data_] := Module[{a, b, s, f, lbf, bf, post},
a = ab[[1]];
b = ab[[2]];
s = data[[1]];
f = data[[2]];
lbf = s * Log[p0] + f * Log[1 - p0] + Log@Beta[a, b] - Log@Beta[a + s, b + f];
bf = Exp[lbf];
post = prob * bf / (prob * bf + 1 - prob);
<|"bf" -> bf, "post" -> post|>
]
(* 関数fの定義 *)
f[alpha_] := pbetat[1/6, 0.5, {alpha, 5*alpha - 4}, {4, 50 - 4}]["post"]
(* 最小化 *)
result = NMinimize[{f[alpha], 0 <= alpha <= 20}, alpha]
856: 05/30(金)20:13 ID:zoAuXcvc(3/3) AAS
p_post_null <- function(p0, prior, alpha, beta, success, failure){
# Calculate the total number of trials from successes and failures.
total = success + failure
# Calculate the likelihood of the data under the null hypothesis (H0).
# This assumes a binomial distribution where the success probability is p0.
m0 = dbinom(success, total, p0)
# Calculate the marginal likelihood of the data under the alternative hypothesis (H1).
# Under H1, the success probability is assumed to follow a Beta distribution
# with parameters alpha and beta. This function (from the 'extraDistr' package)
# computes the marginal likelihood by integrating over all possible success probabilities.
m1 = extraDistr::dbbinom(success, total, alpha, beta)
# Calculate the Bayes Factor (BF01).
# This is the ratio of the likelihood under the null hypothesis (m0)
# to the marginal likelihood under the alternative hypothesis (m1).
BF01 = m0 / m1
# Calculate the posterior probability of the null hypothesis.
# This updates the prior belief (prior) based on the evidence from the data (BF01).
p_post = prior * BF01 / (prior * BF01 + 1 - prior)
# Return both the Bayes Factor and the posterior probability as a named vector.
c(BF01 = BF01, p_post = p_post)
}
# Optimize the 'alpha' parameter to maximize the posterior probability of the null hypothesis.
# We're trying to find the 'alpha' value (within the range 0 to 1e6) that makes the
# null hypothesis most plausible, given the data and the relationship beta = 5*alpha - 4.
# p_post_null(...)[2] specifically extracts the 'p_post' value from the function's output.
optimize(function(alpha) p_post_null(p0 = 1/6,
prior = 1/2,
alpha,
5 * alpha - 4, # Beta parameter is a function of alpha
success = 4,
failure = 50 - 4)[2],
c(0, 1e6)) # Search range for alpha
# Calculate the Bayes Factor and posterior probability using specific alpha and beta values.
# These specific values (alpha = 50/9, beta = 5*50/9 - 4) are likely the result of the
# optimization step above, or pre-determined values that are of interest.
p_post_null(1/6, 1/2, 50/9, 5 * 50/9 - 4, 4, 50 - 4)
857: 05/31(土)05:25 ID:jzcOJBMt(1) AAS
#' @title ベイズ事後確率計算関数
#' @description 帰無仮説と対立仮説の事後確率を計算
#' @param s 観測成功数(1の目が出た回数)
#' @param n 総試行回数
#' @param p0 帰無仮説の確率(例: 1/6)
#' @param prior 帰無仮説の事前確率(0~1)
#' @param alpha 対立仮説のベータ分布αパラメータ
#' @param beta 対立仮説のベータ分布βパラメータ
#' @return list(bf01=ベイズファクター, post=事後確率, method=使用手法)
calculate_posterior <- function(s, n, p0, prior, alpha, beta) {
# 入力検証
stopifnot(
s >= 0, n > 0,
p0 > 0 && p0 < 1,
prior >= 0 && prior <= 1,
alpha > 0, beta > 0
)
# 帰無仮説の尤度計算
m0 <- dbinom(s, n, p0)
# 対立仮説の周辺尤度計算(extraDistr有無で自動切替)
if (requireNamespace("extraDistr", quietly = TRUE)) {
m1 <- extraDistr::dbbinom(s, n, alpha, beta)
method <- "extraDistr::dbbinom()"
} else {
integrand <- function(p) dbinom(s, n, p) * dbeta(p, alpha, beta)
m1 <- integrate(integrand, 0, 1)$value
method <- "数値積分"
}
# ベイズファクターと事後確率計算(指定された式を使用)
bf01 <- m0 / m1
post <- m0 * prior / (m0 * prior + (1 - prior) * m1)
# 結果をリストで返す
list(
bf01 = bf01,
post = post,
method = method,
inputs = list(s = s, n = n, p0 = p0, prior = prior, alpha = alpha, beta = beta),
likelihoods = list(m0 = m0, m1 = m1)
)
}
858: 06/01(日)07:35 ID:/PZFDI/g(1/2) AAS
auc = integrate(unnorm_posterior,0,Inf)$value
integrate(\(x) x*unnorm_posterior(x)/auc, 0,Inf)
log_auc <- log(integrate(\(x) exp(log(unnorm_posterior(x))), 0, Inf)$value)
integrate(\(x) x * exp(log(unnorm_posterior(x)) - log_auc), 0, Inf)$value
859: 06/01(日)09:23 ID:9o1m2vAK(1) AAS
Calculate the marginal likelihood of the data under the alternative hypothesis (H1).
wwwwwwwwwwwwwwwwwwwwwwwwwwwwww
あほ~~
wwwwwwwwwwwwwwwwwwwwwwwwwwwwww
860: 06/01(日)10:41 ID:/PZFDI/g(2/2) AAS
はい、Gelmanらの推奨は確かに進化しており、近年ではハーフt分布(half-t)がより一般的に推奨されています。この変化の背景と具体的な推奨内容を、理論的根拠と実践的なアドバイスに分けて解説します。
1. Gelmanの推奨の変遷
(1) 初期(2006年頃): ハーフコーシー(自由度ν=1)の推奨
推奨理由:
分散パラメータの弱情報事前分布として適切
裾が重く、極端な値への過剰なペナルティを回避
問題点:
自由度ν=1ではスケールの選択に敏感
小規模データで不安定になる可能性
(2) 近年(2013年以降): 自由度ν>1のハーフt分布へ移行
推奨理由:
自由度ν=3〜7でより安定した推定が可能
スケールパラメータの影響が緩和
代表的な論文:
Gelman et al. (2013), "The Prior Can Often Only Be Understood in the Context of the Likelihood"
861: 06/02(月)11:14 ID:GMuHFUYr(1/2) AAS
x = c(-0.86, -0.3, -0.05, 0.73)
n = c(5, 5, 5, 5)
y = c(0, 1, 3, 5)
(data = cbind(x, n, y))
(response = cbind(y, n - y) )
results = glm(response ~ x, family = binomial)
#summary(results)
-results$coef[1]/results$coef[2]
library(MASS) # mvrnorm を使うため
# 推定された係数と共分散行列
beta_hat = coef(results)
(vcov_matrix = vcov(results))
# 多変量正規乱数を生成(β0, β1)
set.seed(123) # 再現性のため
samples = mvrnorm(n = 10000, mu = beta_hat, Sigma = vcov_matrix)
# 各サンプルから LD50 を計算
LD50_samples = -samples[,1] / samples[,2]
# 信頼区間(95%)
CI = quantile(LD50_samples, probs = c(0.025, 0.975))
# 結果表示
cat("シミュレーションによるLD50の95%信頼区間:\n")
print(CI)
862: 06/02(月)12:04 ID:GMuHFUYr(2/2) AAS
# データ
x <- c(-0.86, -0.3, -0.05, 0.73)
n <- c(5, 5, 5, 5)
y <- c(0, 1, 3, 5)
# JAGSモデル
model_string <- "
model {
for (i in 1:N) {
y[i] ~ dbin(p[i], n[i])
logit(p[i]) <- beta0 + beta1 * x[i]
}
# 事前分布(非情報的)
beta0 ~ dnorm(0.0, 0.001)
beta1 ~ dnorm(0.0, 0.001)
# LD50の定義
LD50 <- -beta0 / beta1
}
"
# JAGSに渡すデータ
data_jags <- list(
x = x,
n = n,
y = y,
N = length(y)
)
# 初期値
inits <- function() {
list(beta0 = rnorm(1, 0, 1), beta1 = rnorm(1, 0, 1))
}
# モデル作成と実行
model <- jags.model(textConnection(model_string), data = data_jags, inits = inits, n.chains = 3)
update(model, 1000) # バーンイン
# サンプリング
samples <- coda.samples(model, variable.names = c("beta0", "beta1", "LD50"), n.iter = 10000)
# 結果表示(LD50の95%信用区間)
summary(samples)
LD50_samples <- as.matrix(samples)[, "LD50"]
quantile(LD50_samples, probs = c(0.025, 0.975))
plot(samples)
863: 06/03(火)00:31 ID:CfA5PBxZ(1/2) AAS
x = c(-0.86, -0.3, -0.05, 0.73)
n = c(5, 5, 5, 5)
y = c(0, 1, 3, 5)
(data = cbind(x, n, y))
(response = cbind(y, n - y) )
results = glm(response ~ x, family = binomial(link="logit") )
summary(results)
b=MASS::mvrnorm(1e5,results$coef,S=vcov(results))
# log(p/(1-p)) = b1+b2*x
LD = function(b1,b2,p=0.5) (log(p/(1-p)) - b1)/b2
LD50=mapply(LD,b[,1],b[,2])
hist(LD50)
quantile(LD50,c(0.025,0.5,0.975))
HDInterval::hdi(LD50)
864: 06/03(火)23:40 ID:CfA5PBxZ(2/2) AAS
k=10
m=400
Nmax=1000
sim = \(){
N=sample(m:Nmax,1)
if(max(sample(1:N,k))==m) return(N)
}
N=NULL
while(length(N)<1000) N=c(N,sim())
summary(N)
quantile(N,c(0.5,0.95))
865: 06/04(水)07:49 ID:n75lIIio(1) AAS
set.seed(123)
solve = function(x,k=1e5){
f = function(x) runif(1,x-0.5,x+0.5)
y=replicate(k,mean(sapply(x,f)))
quantile(y,p=c(0.025,0.975))
}
solve(c(9,10,11,11,12))
set.seed(123) # 再現性のため
solve2 <- function(x, k = 1e5) {
# 各x_iに対して一様乱数を生成し、平均を計算(ブートストラップ)
bootstrap_means <- replicate(k, {
x_true <- runif(length(x), x - 0.5, x + 0.5)
mean(x_true)
})
# 95%信頼区間を計算
quantile(bootstrap_means, probs = c(0.025, 0.975))
}
# 実行例
x_rounded <- c(9, 10, 11, 11, 12)
solve2(x_rounded)
866: 06/05(木)13:25 ID:tGlaBVfa(1) AAS
> stancode(fit)
// generated with brms 2.22.0
functions {
/* compute monotonic effects
* Args:
* scale: a simplex parameter
* i: index to sum over the simplex
* Returns:
* a scalar between 0 and rows(scale)
*/
real mo(vector scale, int i) {
if (i == 0) {
return 0;
} else {
return rows(scale) * sum(scale[1:i]);
}
}
}
data {
int<lower=1> N; // total number of observations
array[N] int Y; // response variable
int<lower=1> K; // number of population-level effects
matrix[N, K] X; // population-level design matrix
int<lower=1> Kc; // number of population-level effects after centering
int<lower=1> Ksp; // number of special effects terms
int<lower=1> Imo; // number of monotonic variables
array[Imo] int<lower=1> Jmo; // length of simplexes
array[N] int Xmo_1; // monotonic variable
vector[Jmo[1]] con_simo_1; // prior concentration of monotonic simplex
int prior_only; // should the likelihood be ignored?
}
transformed data {
matrix[N, Kc] Xc; // centered version of X without an intercept
vector[Kc] means_X; // column means of X before centering
for (i in 2:K) {
means_X[i - 1] = mean(X[, i]);
Xc[, i - 1] = X[, i] - means_X[i - 1];
}
}
parameters {
vector[Kc] b; // regression coefficients
real Intercept; // temporary intercept for centered predictors
simplex[Jmo[1]] simo_1; // monotonic simplex
vector[Ksp] bsp; // special effects coefficients
}
transformed parameters {
real lprior = 0; // prior contributions to the log posterior
lprior += normal_lpdf(b[1] | 0.15, 0.3);
lprior += normal_lpdf(b[2] | 0.08, 0.3);
lprior += normal_lpdf(b[3] | 0.8, 0.3);
lprior += normal_lpdf(b[4] | 0.5, 0.3);
lprior += normal_lpdf(Intercept | -4, 2);
lprior += dirichlet_lpdf(simo_1 | con_simo_1);
lprior += normal_lpdf(bsp[1] | -0.5, 0.3);
}
model {
// likelihood including constants
if (!prior_only) {
// initialize linear predictor term
vector[N] mu = rep_vector(0.0, N);
mu += Intercept;
for (n in 1:N) {
// add more terms to the linear predictor
mu[n] += (bsp[1]) * mo(simo_1, Xmo_1[n]);
}
target += bernoulli_logit_glm_lpmf(Y | Xc, mu, b);
}
// priors including constants
target += lprior;
}
generated quantities {
// actual population-level intercept
real b_Intercept = Intercept - dot_product(means_X, b);
}
867: 06/06(金)04:41 ID:fR053ZqC(1/2) AAS
# ロジスティック回帰モデル
ACT = c(16,18,20,22,24,26,28)
n = c(2,7,14,26,13,14,3)
y = c(0,0,6,12,7,9,3)
fit = glm(cbind(y, n - y) ~ ACT, family = binomial())
#predict(fit, newdata = data.frame(ACT = 20)) |> plogis()
predict(fit, newdata = data.frame(ACT = 20)
,type="response")
cat("\n\n===== se.fit=TRUE =====\n\n")
pred1=predict(fit, newdata = data.frame(ACT = 20)
,type="response",se.fit=TRUE)
# 信頼区間(response))結果表示
ci=c(pred1$fit - 1.96*pred1$se.fit,pred1$fit + 1.96*pred1$se.fit)
cat("95% 信頼区間: [", ci[1], ",", ci[2], "]\n")
# 予測(log-odds とその標準誤差)
pred = predict(fit, newdata = data.frame(ACT = 20), se.fit = TRUE)
# 信頼区間(log-odds)
log_odds = pred$fit
se = pred$se.fit
lower_log_odds = log_odds - 1.96 * se
upper_log_odds = log_odds + 1.96 * se
# 確率(ロジスティック関数で変換)
prob = plogis(log_odds)
lower_prob = plogis(lower_log_odds)
upper_prob = plogis(upper_log_odds)
# 結果表示
cat("95% 信頼区間: [", lower_prob, ",", upper_prob, "]\n")
868: 06/06(金)04:43 ID:fR053ZqC(2/2) AAS
確率は0~1の範囲に制限されるため、直接計算は境界(0や1)に近い場合に不適切(例: 負の値や1超えの可能性)。また、ロジスティック回帰の標準誤差はログオッズスケールで計算されるため、確率スケールでの線形近似は精度が落ちる。
869: 06/06(金)06:49 ID:rCqJxG6F(1) AAS
お前には永遠に確率論なんて無理だよ。
数学Bの統計すらわからないのに。
自分が理解できていないことすら理解できないゴミ
870: 06/06(金)08:42 ID:icvPdYuT(1) AAS
公式当てはめてるだけだからな
じゃあその公式をどうやって証明するかまでは考えが及ばない
やってることは公文式で大学生の演習解いてる中学生と一緒
871(4): 06/12(木)09:46 ID:z7P0Lqdi(1) AAS
Bayesian Computation with RでRのコードが理解できなかった。バグだとおもったのだが、
外部リンク[txt]:bayesball.github.io
のerrataにも掲載がないのでAIに聞いてみた。
>>
対数ヤコビアン項が間違っていると思う。
# theta=c(log(eta/(1-eta)),log(K))
> LearnBayes::betabinexch
function (theta, data)
{
eta = exp(theta[1])/(1 + exp(theta[1]))
K = exp(theta[2])
y = data[, 1]
n = data[, 2]
N = length(y)
logf = function(y, n, K, eta) lbeta(K * eta + y, K * (1 -
eta) + n - y) - lbeta(K * eta, K * (1 - eta))
val = sum(logf(y, n, K, eta))
val = val + theta[2] - 2 * log(1 + exp(theta[2]))
return(val)
}
<bytecode: 0x000001a5a980e758>
<environment: namespace:LearnBayes>
これが正しいのでは?
betabinexch <- function (theta, data)
{
eta = exp(theta[1])/(1 + exp(theta[1]))
K = exp(theta[2])
y = data[, 1]
n = data[, 2]
N = length(y)
logf = function(y, n, K, eta)
lbeta(K * eta + y, K * (1 - eta) + n - y) - lbeta(K * eta, K * (1 - eta))
val = sum(logf(y, n, K, eta))
val = val + theta[1] + theta[2] - 2 * log(1 + exp(theta[1])) # log Jacobian term
return(val)
}
<<
いずれのAIも
>あなたの指摘は正しいです。対数ヤコビアン項に問題があります。
という趣旨の返事が返ってきた。
872: 06/12(木)18:10 ID:CDb/RdAY(1/2) AAS
>>871
脳内医者完全にバレたのにまだ頑張ってるんだ
哀れだね
873: 06/12(木)18:20 ID:QiRqli9X(1) AAS
>>871
バグだと思ったのにIssueもあげないの?
スレの私的利用といい、マジで他人の成果やタイトルに乗っかるだけの寄生虫じゃん
税金も年金もコイツに使うだけ無駄だよ
874(1): 06/12(木)18:27 ID:CDb/RdAY(2/2) AAS
>>871に質問!
当然入試でも満点が取れる解答以外認めません
①円周率が3.05より大きいことを証明せよ。
ただし円周率は(円周)/(円の直径)と定義され、円周率が3.14より大きい事は判明していないものとする。
②√2+√3が無理数であることを証明せよ。
875: 06/13(金)07:38 ID:XjvE6Ide(1) AAS
>>874
証明問題解けないんだから、人のした証明が正しいかの判断できないだろ
876(2): 06/14(土)05:53 ID:nWbGzc8A(1) AAS
(1)nを正整数とする。
n^3+4n^2+3nを6で割った余りを求めよ。
(2)nを正整数とする。
n^3+7n^2+5nを6で割った余りを求めよ。
877: 06/14(土)10:23 ID:c0/MskJB(1) AAS
>>876
(2)が傑作でございます
878: 06/15(日)01:22 ID:bEUsomGs(1) AAS
>>876
n^3+7n^2+5n
=n(n^2+7n+5)
=n{(n+1)(n+2)+3(n+1)+n}
・n(n+1)(n+2)は3連続の正整数の積なので6の倍数
・n(n+1)は偶数なので3n(n+1)は6の倍数
したがってn^3+7n^2+5nを6で割った余りはn^2を6で割った余りに等しい。
n=6kのとき、求める余りは0
n=6k+1のとき、求める余りは1
n=6k+2のとき、求める余りは4
n=6k+3のとき、求める余りは3
n=6k+4のとき、求める余りは4
n=6k+5のとき、求める余りは1
879: 06/15(日)08:32 ID:MIIBNstg(1) AAS
pdf2hdi <- function(pdf,
xMIN=0,
xMAX=1,
cred=0.95,
Print=TRUE,
nxx=1001){
xx=seq(xMIN,xMAX,length=nxx)
xx=xx[-nxx]
xx=xx[-1]
xmin=xx[1]
xmax=xx[nxx-2]
AUC=integrate(pdf,xmin,xmax)$value
PDF=function(x)pdf(x)/AUC
cdf <- function(x) integrate(PDF,xmin,x)$value
ICDF <- function(x) uniroot(function(y) cdf(y)-x,c(xmin,xmax))$root
ICDF=Vectorize(ICDF)
hdi=HDInterval::hdi(ICDF,credMass=cred)
print(c(hdi[1],hdi[2]),digits=5)
if(Print){
par(mfrow=c(3,1))
plot(xx,sapply(xx,PDF),main='pdf',type='h',xlab='x',ylab='Density',col='lightgreen',bty='l')
legend('top',bty='n',legend=paste('HDI:',round(hdi,3)))
plot(xx,sapply(xx,cdf),main='cdf',type='h',xlab='x',ylab='Probability',col='lightblue',bty='l')
pp=seq(0,1,length=nxx)
pp=pp[-nxx]
pp=pp[-1]
plot(pp,sapply(pp,ICDF),type='l',xlab='p',ylab='x',main='ICDF',bty='l')
par(mfrow=c(1,1))
}
invisible(ICDF)
}
ICDF=pdf2hdi(function(x) dbeta(x,2,5))
hist(ICDF(seq(1e-12,1-1e-12,le=1000)))
AIの評価
まとめ
この pdf2hdi 関数は、数値積分と数値最適化 (uniroot) を巧みに組み合わせることで、任意のPDFからICDFを頑健に導出し、さらに統計的な要約であるHDIを計算する、非常に実用的かつ教育的なコードです。両端での数値計算の回避や正規化といった細部への配慮も素晴らしいです。
これにより、複雑な確率分布でも、そこからサンプリングしたり、HDIを求めたりといった解析が可能になります。
上下前次1-新書関写板覧索設栞歴
あと 123 レスあります
スレ情報 赤レス抽出 画像レス抽出 歴の未読スレ
ぬこの手 ぬこTOP 0.027s