{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# IntroStat Week 5\n", "\n", "Example: voltage drop" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import matplotlib.pyplot as plt\n", "import scipy.stats as stats" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Enter data\n", "x = np.array([0.75,-0.85,4.23,2.12,3.04,0.53,-0.35,1.69,1.52,-0.42])\n", "n = len(x)\n", "print(x)\n", "print(n)\n", "plt.hist(x)\n", "plt.show()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Compute best estimate for the mean (and the standard error)\n", "mean_hat = x.mean()\n", "se_mean = x.std(ddof=1)/np.sqrt(n)\n", "print([mean_hat, x.std(ddof=1), se_mean])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# confidence interval for the mean:\n", "mu_lower = mean_hat - stats.t.ppf(0.975, df=9)*se_mean\n", "mu_upper = mean_hat + stats.t.ppf(0.975, df=9)*se_mean\n", "print([mu_lower, mu_upper])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Margin of Error:\n", "print(stats.t.ppf(0.975, df=9)*se_mean)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Define the null hypothesis\n", "mean_null_hyp = 0" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Compute the \"test statistic\" from the oberserved data\n", "tobs = (mean_hat - mean_null_hyp) / se_mean\n", "print(tobs)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# compare with t_0.975 from t-distribution with df = 9\n", "stats.t.ppf(0.975, df=n-1)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# calculate p-value\n", "2*stats.t.cdf(-tobs, df=n-1)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# You can also use the ttest_1samp funtion from scipy.stats:\n", "print(stats.ttest_1samp(x, popmean=0))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(stats.ttest_1samp(x, popmean=0).confidence_interval(confidence_level=0.95))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(stats.ttest_1samp(x, popmean=0).confidence_interval(confidence_level=0.99))" ] } ], "metadata": { "kernelspec": { "display_name": "Pernille_Env_python_311", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.13" } }, "nbformat": 4, "nbformat_minor": 2 }