import numpy as np
from scipy.stats import t
def ttest_1samp(x, mean_null = 0):
"""
Perform two-sided one-sample t-test.
Parameters:
- x: The sample for the test.
- mean_null: The null hypothesis value (default is 0).
Returns:
- res: A dictionary containing the results of the test.
"""
# Ensure x is NumPy array
x = np.array(x)
mean_x = np.mean(x)
# Use ddof = 1 for sample variance in Python
var_x = np.var(x, ddof = 1)
n_x = len(x)
se_x = np.sqrt(var_x / n_x)
# Calculate the t-statistic
t_stat = (mean_x - mean_null) / se_x
# Calculate the degrees of freedom
df = n_x - 1
# Calculate the p-value
p_val = 2 * (1 - t.cdf(abs(t_stat), df))
# Create a result dictionary
res = {
't_statistic': t_stat,
'p_value': p_val
}
return res