<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by RamuMadireddy on Medium]]></title>
        <description><![CDATA[Stories by RamuMadireddy on Medium]]></description>
        <link>https://medium.com/@ramumadireddy1072?source=rss-f08e3b6f3210------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*d7chEhR-Q3twAo_P</url>
            <title>Stories by RamuMadireddy on Medium</title>
            <link>https://medium.com/@ramumadireddy1072?source=rss-f08e3b6f3210------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 21:11:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ramumadireddy1072/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[CORRELATION AND LINEAR REGRESSION]]></title>
            <link>https://medium.com/@ramumadireddy1072/correlation-and-linear-regression-80881c985af5?source=rss-f08e3b6f3210------2</link>
            <guid isPermaLink="false">https://medium.com/p/80881c985af5</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[RamuMadireddy]]></dc:creator>
            <pubDate>Thu, 03 Dec 2026 11:30:30 GMT</pubDate>
            <atom:updated>2026-12-03T11:30:30.245Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>1. Introduction</strong></h3><p>Correlation and regression are two important statistical methods used to investigate the relationship between two variables. They are widely applied in statistics, economics, engineering, science, and data analysis to understand how variables are associated and how one variable can be used to predict another.</p><p>Correlation measures the strength and direction of the linear relationship between two variables. It indicates whether the variables tend to increase together, move in opposite directions, or have no linear association.</p><p>Regression, on the other hand, describes the relationship between variables through a mathematical equation. It allows us to estimate or predict the value of one variable based on the observed value of another variable.</p><p>Although correlation and regression are closely related, they have different purposes. Correlation measures association, whereas regression provides a mathematical model for explaining and predicting relationships.</p><p>The main objectives of this assignment are:</p><ul><li>To explain the concept of correlation and its relationship with regression.</li><li>To calculate the two regression lines for a dataset containing two variables.</li><li>To determine the regression coefficients and verify their relationship with the correlation coefficient.</li><li>To prove mathematically that independence between two random variables implies zero correlation.</li><li>To understand why zero correlation does not necessarily mean independence.</li></ul><h3>2. Concept of Correlation</h3><p>Correlation is a statistical measure that describes the degree and direction of association between two variables, usually represented by X and Y.</p><p>The most commonly used measure is the Pearson correlation coefficient, represented by the symbol r for sample data or ρ for population data.</p><p>The correlation coefficient always lies between -1 and +1.</p><h3>2.1 Types of correlation</h3><p><strong>Positive correlation</strong></p><p>Positive correlation occurs when two variables tend to increase or decrease together. For example, an increase in the number of hours spent studying may be associated with an increase in examination marks.</p><p>In this case, the correlation coefficient is positive:</p><ul><li>If r is close to +1, the positive linear relationship is strong.</li><li>If r is close to 0, the positive linear relationship is weak.</li></ul><p><strong>Negative correlation</strong></p><p>Negative correlation occurs when one variable tends to increase while the other decreases. For example, an increase in the speed of a vehicle may be associated with a decrease in the time required to travel a fixed distance.</p><p>In this case, the correlation coefficient is negative:</p><ul><li>If r is close to -1, the negative linear relationship is strong.</li><li>If r is close to 0, the negative linear relationship is weak.</li></ul><p><strong>Zero correlation</strong></p><p>Zero correlation means that there is no linear association between the two variables. However, it does not necessarily mean that the variables are completely unrelated because a nonlinear relationship may still exist.</p><h3>2.2 Pearson correlation coefficient</h3><p>The Pearson correlation coefficient is calculated using the covariance between X and Y divided by the product of their standard deviations.</p><p><strong>LaTeX formula:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/156/1*Wlr78kYuM9pty7JBdU2GOg.png" /></figure><p>For a sample dataset, the equivalent computational formula is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/138/1*ez3CaMR815wox7oik-O8mg.png" /></figure><p>Where:</p><ul><li>Sxy represents the sum of cross-deviations.</li><li>Sxx represents the sum of squared deviations of X.</li><li>Syy represents the sum of squared deviations of Y.</li></ul><p>The coefficient provides information about the direction and strength of the linear relationship.</p><p>An important limitation is that correlation does not establish causation.</p><h3>3. Relationship Between Correlation and Regression</h3><p>Correlation and regression are related statistical techniques, but they describe the relationship between variables from different perspectives.</p><p>Correlation is a symmetric measure. This means that the correlation between X and Y is the same as the correlation between Y and X.</p><p>Regression is not symmetric because it distinguishes between an independent or explanatory variable and a dependent or response variable.</p><p>For two variables X and Y, there are two regression lines:</p><ol><li>Regression of Y on X.</li><li>Regression of X on Y.</li></ol><p>The first line is used to estimate Y when X is known. The second line is used to estimate X when Y is known.</p><p>Both regression lines pass through the point of means, which is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/72/1*_wpygMZpPejbn3AiXKRi0A.png" /></figure><p>The correlation coefficient and the regression coefficients are connected mathematically. Their relationship is particularly useful because it allows us to verify the results obtained from the two regression equations.</p><p>When the correlation is positive, both regression coefficients are positive. When the correlation is negative, both regression coefficients are negative.</p><p>The two regression lines become closer to each other as the absolute value of correlation approaches 1. When the correlation is exactly +1 or -1, the two regression lines coincide.</p><h3>4. Linear Regression and the Calculation of Coefficients</h3><p>Linear regression is a statistical method used to represent the relationship between two variables using a straight line.</p><p>The general equation of a straight line is:</p><p>Y = a + bX</p><p>Where:</p><ul><li>Y is the dependent variable.</li><li>X is the independent variable.</li><li>a is the intercept.</li><li>b is the regression coefficient or slope.</li></ul><p>The intercept represents the estimated value of Y when X is zero. The slope indicates the expected change in Y for a one-unit increase in X.</p><h3>4.1 Least squares method</h3><p>The regression line is generally determined using the least-squares method.</p><p>The method finds the line that minimizes the sum of the squared differences between the observed values and the values predicted by the regression equation.</p><p>The sum of squared errors is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*dcCXQQNgYltpCva_Cmhl0g.png" /></figure><p>To minimize this expression, we calculate the partial derivatives with respect to a and b and set them equal to zero.</p><p>This produces the following normal equations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*gfNsZwkTG2g1HCeBv7xxjA.png" /></figure><p>Solving these equations gives the regression coefficients.</p><p>The slope is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/122/1*DDerq28Tz7x3o-ma21sSNw.png" /></figure><p>The intercept is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/143/1*mCCIIOIKI5G09fA55VXJpQ.png" /></figure><p>Therefore, the regression equation of Y on X and the regression equation of X on Y is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/152/1*yITi78uJ18gv0NiNfDvEEA.png" /></figure><p>Its coefficients are calculated as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/157/1*LoY5VJKgwYSn7D5o8AHPJg.png" /></figure><p>It is important to calculate both regression equations separately because each equation minimizes the squared prediction errors in a different direction.</p><h3>5. Numerical Example: Calculation of Both Regression Lines</h3><h3>5.1 Calculation of the means</h3><p>The mean of X is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/97/1*yNP6rutowOu76PZM7Dwgng.png" /></figure><p>The mean of Y is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/92/1*-ZUfgzi34aSJML4uja85AQ.png" /></figure><h3>5.2 Calculation of deviations</h3><p>To calculate the regression coefficients, we first determine the deviations of each observation from its corresponding mean.</p><p>The required calculations are shown in the following table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*K8ToYl0NejZ7sh-EQaskeg.png" /></figure><p>From the table, we obtain:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*07fT-Srw14eEKphAc5QfZw.png" /></figure><p>These three values are used to calculate the regression coefficients and the correlation coefficient.</p><h3>6. Verification: Correlation Coefficient as the Geometric Mean of Regression Coefficients</h3><p>One of the important properties of correlation and regression is that the correlation coefficient is equal to the signed geometric mean of the two regression coefficients.</p><p>The mathematical relationship is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/182/1*d1UGX0k9_V29C_ghxMJ1xw.png" /></figure><p>The sign must be the same as the sign of the regression coefficients.</p><p>Now, we independently calculate the Pearson correlation coefficient using the covariance based formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/140/1*ZNkXFNHUQO5sV4Z2thPyZA.png" /></figure><p>This confirms that the correlation coefficient is equal to the geometric mean of the two regression coefficients, with the appropriate sign.</p><h3>6. Proof: Independence Implies Uncorrelation</h3><p>Independence and uncorrelation are two different statistical concepts.</p><p>Two random variables X and Y are independent if knowing the value of one variable does not provide information about the probability distribution of the other variable.</p><p>Uncorrelation means that the covariance between the two variables is zero.</p><p>We now prove mathematically that independence implies uncorrelation, assuming the variables have finite second moments.</p><h3>6.1 Definition of independence</h3><p>Two random variables X and Y are independent if their joint probability distribution is equal to the product of their marginal distributions.</p><p>For discrete random variables:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*BkTud7ris3D49K__S9I0Og.png" /></figure><p>For independent random variables with the required finite expectations, this property implies:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/191/1*SO8NllAuO4Rn4yPee7kXuw.png" /></figure><p>This is the key property used in the proof.</p><h3>6.2 Definition of covariance</h3><p>The covariance between X and Y measures how the two variables vary together.</p><p>It is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*o6NQb0vz9J0jlv9FUrl0Iw.png" /></figure><h3>7. Conclusion</h3><p>In this work, we explored the concepts of correlation and linear regression and examined their mathematical relationship.</p><p>Correlation measures the strength and direction of the linear association between two variables, while regression provides equations that describe and predict the relationship between them.</p><p>Using a numerical dataset containing six observations, we calculated both regression lines independently.</p><p>Finally, we proved mathematically that independence implies uncorrelation by showing that independent random variables have zero covariance and, under the appropriate conditions, zero correlation.</p><p>Overall, correlation and regression are valuable tools for understanding relationships between variables. However, their results must be interpreted carefully, particularly when distinguishing statistical association from causation and independence.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80881c985af5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modes of Convergence in Probability Theory and Bayesian Statistical Inference]]></title>
            <link>https://medium.com/@ramumadireddy1072/modes-of-convergence-in-probability-theory-and-bayesian-statistical-inference-636459e653cd?source=rss-f08e3b6f3210------2</link>
            <guid isPermaLink="false">https://medium.com/p/636459e653cd</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[RamuMadireddy]]></dc:creator>
            <pubDate>Thu, 26 Nov 2026 14:12:45 GMT</pubDate>
            <atom:updated>2026-11-26T14:12:45.062Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Introduction</h3><p>Probability theory is an important part of statistics because it helps us understand uncertainty and analyse random events. Many statistical methods are based on collecting observations and using them to make conclusions about a larger population. Two important topics in this area are modes of convergence and Bayesian statistical inference.</p><p>Modes of convergence explain how a sequence of random variables approaches a particular value or distribution as the number of observations increases. They are closely connected to two fundamental results in probability theory: the Law of Large Numbers (LLN) and the Central Limit Theorem (CLT).</p><p>Bayesian inference, on the other hand, explains how probabilities can be updated when new information becomes available. It combines previous knowledge with observed data through Bayes’ theorem.</p><h3>2. Modes of Convergence in Probability Theory</h3><p>In probability theory, convergence describes how a sequence of random variables approaches a limiting random variable.</p><p>Suppose we have a sequence: X1, X2, X3, ….., Xn</p><p>We want to understand whether these random variables approach another random variable X as the sample size increases.</p><p>There are four main types of convergence: convergence in probability, almost sure convergence, mean square convergence and convergence in distribution. Although they are related, they describe different aspects of the limiting behaviour.</p><h3>2.1 Convergence in Probability</h3><p>A sequence of random variables converges in probability if the probability that its difference from the limiting value is greater than a small positive number approaches zero.</p><p>It is represented as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/92/1*ILEy0bcUBf7Vljyk2HiNrw.png" /></figure><p>The mathematical definition is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*-RIzaHFg050QYx_pW-WbWQ.png" /></figure><p>In simple terms, this means that as the number of observations increases, the probability of making a large error becomes smaller.</p><p>Convergence in probability is particularly important in statistics because it is used to define consistency. An estimator is consistent when it approaches the true population parameter in probability as the sample size increases.</p><h3>2.2 Almost Sure Convergence</h3><p>Almost sure convergence is a stronger form of convergence than convergence in probability.</p><p>A sequence converges almost surely if it approaches its limiting value with probability one.</p><p>It is written as: and means</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*XePJIzVnXzQufgTJfvcR7A.png" /></figure><p>The term almost surely means that convergence occurs for all outcomes except possibly a set of probability zero.</p><p>This behaviour is explained by the Strong Law of Large Numbers.</p><p>Almost sure convergence is useful when studying the long-term behaviour of random experiments because it describes what happens to almost every possible sequence of observations.</p><h3>2.3 Mean Square Convergence (L²)</h3><p>Mean square convergence, also called quadratic mean convergence, measures how close two random variables are by considering their expected squared difference.</p><p>It is represented as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/1*PTmSAP79NeotFlR_w8-y2A.png" /></figure><p>This means that the average squared error between the sequence and its limiting value approaches zero.</p><p>Unlike convergence in probability, which focuses on the probability of a large error, mean-square convergence also considers the magnitude of the error.</p><p>Mean square convergence also implies convergence in probability, through Chebyshev’s inequality.</p><h3>2.4 Convergence in Distribution</h3><p>Convergence in distribution occurs when the probability distributions of a sequence of random variables approach a limiting distribution.</p><p>It is represented as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/96/1*CiMopd3lWAeaEc_0I-x-Hw.png" /></figure><p>This type of convergence is particularly important in statistical inference because many statistical procedures depend on the distribution of an estimator rather than its exact value.</p><h3>3. Differences and Relationships Between the Four Modes</h3><p>Although all four modes describe convergence, they are not equivalent.</p><p>Their main differences are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*jav10qZZxOx5oMKggdvAEg.png" /></figure><p>There are also important mathematical relationships between them.</p><p>Both almost sure convergence and mean square convergence imply convergence in probability:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*N6xWfOT7pjkprkTXWRgvyg.png" /></figure><p>Convergence in probability also implies convergence in distribution.</p><p>However, the reverse implications do not generally hold.</p><p>It is also important to note that almost sure convergence and mean-square convergence are not generally comparable. Neither automatically implies the other.</p><h3>4. Law of Large Numbers (LLN)</h3><p>The Law of Large Numbers is one of the most important results in probability theory. It explains why the average of a large number of independent observations approaches the expected value of the population.</p><p>Suppose we have independent and identically distributed random variables with mean mu. Their sample mean is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/142/1*Hd_dfdl0CxFqbk5OMx7gRQ.png" /></figure><p>The LLN states that the sample mean approaches the population mean as the sample size increases.</p><p>There are two main versions of this theorem.</p><h3>4.1 Weak Law of Large Numbers</h3><p>The Weak Law of Large Numbers states that the sample mean converges in probability to the population.</p><h3>4.2 Strong Law of Large Numbers</h3><p>The Strong Law of Large Numbers states that the sample mean converges almost surely to the population.</p><h3>5. Central Limit Theorem (CLT)</h3><p>The Central Limit Theorem explains how the distribution of sample means behaves when the sample size becomes sufficiently large.</p><p>Suppose that observations are independent and identically distributed, with mean mu and finite variance sigma².</p><p>The CLT states that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*-tpbZ42OMUHld8A0SaXLqA.png" /></figure><p>This means that the standardised sample mean approaches a standard normal distribution, even when the original population does not follow a normal distribution, provided the theorem’s assumptions are satisfied.</p><p>The CLT is extremely useful because it allows statisticians to calculate probabilities, construct confidence intervals and perform hypothesis tests without requiring the original population to be normally distributed.</p><h3>PART II: CONDITIONAL PROBABILITY AND BAYESIAN STATISTICAL INFERENCE</h3><h3>6. Conditional Probability</h3><p>Conditional probability describes the probability of an event occurring when another event is already known to have occurred.</p><p>For two events A and B, where P(B)&gt;0, conditional probability is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*919Asy0eqsDkOC7ZEGAZmQ.png" /></figure><p>This formula shows how the probability of an event changes when additional information is available.</p><p>Conditional probability is important in medical diagnosis, financial risk analysis, machine learning and many other applications.</p><h3>7. Bayes’ Theorem</h3><p>Bayes’ theorem is a fundamental rule of probability that explains how to update the probability of an event when new evidence becomes available.</p><p>It is expressed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*4A6wRqxTYt31MZIAi7Kqyw.png" /></figure><p>The theorem connects the probability of an event before observing evidence with its probability after observing that evidence.</p><p>It is particularly useful in situations where we want to determine the possible cause of an observed result.</p><h3>8. The Three Main Components of Bayesian Inference</h3><p>Bayesian inference is based on three fundamental components: prior probability, likelihood and posterior probability.</p><h3>8.1 Prior Probability</h3><p>The prior probability represents what we know or believe about an event or parameter before observing new data.</p><p>It is represented by: P(A)</p><p>In Bayesian statistics, prior information is often represented using a probability distribution rather than a single value.</p><h3>8.2 Likelihood</h3><p>The likelihood describes how compatible the observed data are with a particular value of an unknown parameter.</p><p>It is written as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*QCYdGAuKXrrXvV1fwbT9ZA.png" /></figure><p>Here, theta represents the unknown probability of obtaining heads.</p><h3>9. Conclusion</h3><p>Modes of convergence and Bayesian inference are two important areas of probability theory that help explain uncertainty in statistical analysis.</p><p>The four modes of convergence describe different ways in which random variables approach a limit. Convergence in probability, almost sure convergence, mean square convergence and convergence in distribution each have different mathematical meanings and applications.</p><p>The Law of Large Numbers explains why sample averages approach population means, while the Central Limit Theorem describes the distribution of sample means for large samples.</p><p>The appearance of sqrt{n} is mainly connected to the additivity of variance for independent observations. It explains why the standard error of the sample mean decreases at the rate of 1/sqrt{n}, making larger samples generally more precise.</p><p>Bayesian inference provides another important approach to statistical uncertainty. Through Bayes’ theorem, prior knowledge and observed data are combined to obtain posterior probabilities. The medical testing and coin-tossing examples demonstrate how this process can improve statistical conclusions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=636459e653cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Homework 6: Statistical Independence]]></title>
            <link>https://medium.com/@ramumadireddy1072/homework-6-statistical-independence-4712c988fb3f?source=rss-f08e3b6f3210------2</link>
            <guid isPermaLink="false">https://medium.com/p/4712c988fb3f</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[RamuMadireddy]]></dc:creator>
            <pubDate>Wed, 18 Nov 2026 15:56:25 GMT</pubDate>
            <atom:updated>2026-11-18T15:56:25.877Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Contingency Tables, Expected Frequencies and the Chi-square Test</em></p><h3>1. Introduction</h3><p>Statistical independence helps us determine whether two categorical variables are related.</p><p>For this assignment, I use a small illustrative dataset to investigate the relationship between <strong>study method</strong> and <strong>exam outcome</strong>.</p><ul><li><strong>X:</strong> Study method (A or B)</li><li><strong>F:</strong> Exam result (Pass or Fail)</li></ul><p>The objective is to construct a contingency table, calculate marginal and conditional frequencies, determine expected frequencies under independence, and perform the Chi-square test.</p><h3>2. Theoretical Background</h3><p>Two events A and B are independent if:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*fKPn3UTtezdekY-lcooo9w.png" /></figure><p>This means that the occurrence of one event does not affect the probability of the other.</p><p>The conditional probability is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*HfBCDrqs24bBYaj1KbpHDw.png" /></figure><p>For two categorical variables, independence means that the conditional distribution of one variable remains the same across the categories of the other variable.</p><p>The expected frequency under independence is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/117/1*lp7pQHk9IEsxB-w8xFA9lw.png" /></figure><p>The Pearson Chi-square statistic is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/1*1-u4HEAHl9ZoHIStLyv-9Q.png" /></figure><p>The degrees of freedom are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/1*HyRwX6MN-GXGzbOnhcrdgQ.png" /></figure><h3>3. Dataset and Python Implementation</h3><p>For this example, I use 40 hypothetical observations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*Oov8t9RvWbNfgZhg_yrXXg.png" /></figure><p><strong>Python code:</strong></p><pre>import pandas as pd<br>import numpy as np<br>from scipy.stats import chi2_contingency<br><br># Create the dataset<br>data = (<br>    [(&quot;A&quot;, &quot;Pass&quot;)] * 12 +<br>    [(&quot;A&quot;, &quot;Fail&quot;)] * 8 +<br>    [(&quot;B&quot;, &quot;Pass&quot;)] * 4 +<br>    [(&quot;B&quot;, &quot;Fail&quot;)] * 16<br>)<br><br>df = pd.DataFrame(<br>    data, columns=[&quot;Study_Method&quot;, &quot;Exam_Result&quot;]<br>)<br><br># Construct contingency table<br>table = pd.crosstab(<br>    df[&quot;Study_Method&quot;], df[&quot;Exam_Result&quot;]<br>)<br><br>print(&quot;Observed frequencies:&quot;)<br>print(table)<br><br># Marginal frequencies<br>print(&quot;\nMarginal frequencies:&quot;)<br>print(table.sum(axis=1))<br>print(table.sum(axis=0))<br><br># Conditional frequencies<br>print(&quot;\nExam result given study method:&quot;)<br>print(table.div(table.sum(axis=1), axis=0))<br><br># Expected frequencies and Chi-square test<br>chi2, p, dof, expected = chi2_contingency(<br>    table, correction=False<br>)<br><br>print(&quot;\nExpected frequencies:&quot;)<br>print(pd.DataFrame(<br>    expected, index=table.index, columns=table.columns<br>))<br><br>print(&quot;\nChi-square:&quot;, chi2)<br>print(&quot;Degrees of freedom:&quot;, dof)<br>print(&quot;P-value:&quot;, p)<br><br># Cramer&#39;s V<br>n = table.to_numpy().sum()<br>v = np.sqrt(chi2 / (n * min(table.shape[0]-1,<br>                            table.shape[1]-1)))<br><br>print(&quot;Cramer&#39;s V:&quot;, v)</pre><h3>4. Results and Interpretation</h3><p>The marginal frequencies show that 16 observations passed and 24 failed.</p><p>The conditional frequencies are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*r8HxmEWb_JUTsxNE2GDacQ.png" /></figure><p>The pass rate is higher for method A than method B, suggesting a possible association between the two variables.</p><p>Under the assumption of independence, the expected frequencies are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*VnKwsxOHrMnPnfRmAv1Dfg.png" /></figure><p>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*NI0mEc5OZeHu9p6BPXMA5w.png" /></figure><h3>Chi-square test</h3><p>We define the hypotheses:</p><ul><li><strong>H₀:</strong> Study method and exam outcome are independent.</li><li><strong>H₁:</strong> Study method and exam outcome are dependent.</li></ul><p>Chi-square statistic — — — — — — 6.6667</p><p>Degrees of freedom — — — — — — 1</p><p>P-value — — — — — — — — — — — — 0.0098</p><p>Cramér’s V — — — — — — — — — — 0.4082</p><p>Since the p-value (0.0098) is smaller than the significance level of 0.05, we reject the null hypothesis.</p><p>Therefore, there is statistically significant evidence of an association between study method and exam outcome.</p><p>Cramér’s V of approximately 0.408 indicates a noticeable association between the variables.</p><h3>5. Association Does Not Mean Causation</h3><p>Although the results show an association, they do not prove that study method directly causes better exam results.</p><p>Other factors, such as previous knowledge, preparation time, attendance and individual ability, may influence exam performance.</p><p>A controlled work would be needed to investigate whether the study method itself causes a difference.</p><h3>6. Conclusion</h3><p>In this homework, I constructed a contingency table using Python and calculated marginal and conditional frequencies, expected frequencies and the Pearson Chi-square statistic.</p><p>The test produced a Chi-square value of 6.6667 and a p-value of 0.0098. Since the p-value is below 0.05, the null hypothesis of independence is rejected.</p><p>The results indicate that study method and exam outcome are statistically associated in this illustrative dataset. However, this does not necessarily imply a causal relationship.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4712c988fb3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Numerical Integration and the Standard Normal CDF]]></title>
            <link>https://medium.com/@ramumadireddy1072/numerical-integration-and-the-standard-normal-cdf-d6d24734cb1e?source=rss-f08e3b6f3210------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6d24734cb1e</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[RamuMadireddy]]></dc:creator>
            <pubDate>Wed, 11 Nov 2026 13:28:25 GMT</pubDate>
            <atom:updated>2026-11-11T13:28:25.045Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Introduction</h3><p>Numerical integration and probability distributions are important mathematical tools in statistics and data analysis. In this homework, I investigate two topics: numerical approximations of Riemann and Lebesgue integrals, and numerical computation of the cumulative distribution function (CDF) of the standard normal distribution.</p><p>The main objective is to understand how different numerical methods work, compare their accuracy, and identify their computational limitations.</p><h3>2. Exercise 1 : Riemann and Lebesgue Integration</h3><h3>2.1 Mathematical background</h3><p>Riemann integration divides the domain of a function into small intervals and approximates the area using rectangles.</p><p>For an interval [a,b], the midpoint approximation is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*1tqn3GvlKXVuaoacUJjm2A.png" /></figure><p>In contrast, Lebesgue integration considers the values of the function and measures the corresponding subsets of the domain. Instead of dividing the x-axis into intervals, it divides the range of function values into smaller intervals.</p><p>A numerical approximation inspired by this idea is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/1*bC7sHQvQFudtkvU-ejhZHA.png" /></figure><p>where:</p><ul><li>B is the number of range bins.</li><li>M is the number of sampled domain points.</li><li>y_j^* is the representative value of bin j.</li><li>n_j is the number of sampled points whose function values belong to that bin.</li></ul><p>This is a numerical, range based approximation and should not be confused with a rigorous construction of the Lebesgue integral.</p><h3>2.2 Selected functions and methodology</h3><p>I selected four functions with different mathematical properties:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*DgJzT7b5HB2nhsMYnD9GCw.png" /></figure><p>For the Riemann method, I used 10,000 subintervals and midpoint sampling.</p><p>For the Lebesgue inspired method, I used 200,000 domain samples and 1,000 range bins. This allows the function values to be grouped according to their magnitude.</p><h3>2.3 Python implementation</h3><p>The following code implements both numerical approaches.</p><pre>import numpy as np<br><br>def riemann_midpoint(f, a, b, N=10000):<br>    dx = (b - a) / N<br>    x = a + (np.arange(N) + 0.5) * dx<br>    return dx * np.sum(f(x))<br><br><br>def lebesgue_approx(f, a, b, M=200000, B=1000):<br>    dx = (b - a) / M<br>    x = a + (np.arange(M) + 0.5) * dx<br><br>    y = f(x)<br><br>    ymin, ymax = np.min(y), np.max(y)<br><br>    if ymin == ymax:<br>        return (b - a) * ymin<br><br>    edges = np.linspace(ymin, ymax, B + 1)<br><br>    indices = np.searchsorted(<br>        edges, y, side=&quot;right&quot;<br>    ) - 1<br><br>    indices = np.clip(indices, 0, B - 1)<br><br>    representatives = (<br>        edges[:-1] + edges[1:]<br>    ) / 2<br><br>    counts = np.bincount(<br>        indices, minlength=B<br>    )<br><br>    return (b - a) * np.sum(<br>        representatives * counts / M<br>    )<br><br><br>functions = [<br>    (&quot;sin(x)&quot;, np.sin, 0, np.pi, 2),<br>    (&quot;x^2&quot;, lambda x: x**2, 0, 1, 1/3),<br>    (&quot;abs(x-0.5)&quot;, lambda x: np.abs(x-0.5),<br>     0, 1, 0.25),<br>    (&quot;Step&quot;, lambda x: np.where(x &lt; 0.5, 1, 3),<br>     0, 1, 2)<br>]<br><br>for name, f, a, b, exact in functions:<br><br>    r = riemann_midpoint(f, a, b)<br>    l = lebesgue_approx(f, a, b)<br><br>    print(name)<br>    print(&quot;Exact:&quot;, exact)<br>    print(&quot;Riemann:&quot;, r)<br>    print(&quot;Lebesgue-inspired:&quot;, l)</pre><h3>2.4 Numerical results</h3><p>The numerical results obtained from the implementation are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*Ki_kY6W-NKJuNyINjXWedw.png" /></figure><h3>2.5 Discussion</h3><p>The results show that both numerical approaches can approximate the integral accurately for the selected functions.</p><p>The midpoint Riemann method performs particularly well for smooth functions such as sin(x) and x². Increasing the number of subintervals generally improves its accuracy.</p><p>The range based approach also produces good approximations, but its accuracy depends on the number of range bins and the number of domain samples.</p><p>For the absolute value and step functions, both approaches produce the exact result to the displayed precision because their structures are particularly suitable for these partitions.</p><p>An interesting theoretical example is the Dirichlet function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*m0ZZYh4Z5xKB8-odn8eoaQ.png" /></figure><p>This function is not Riemann integrable because its upper and lower sums remain different for every partition of [0,1].</p><p>However, it is Lebesgue integrable, and its integral is zero because the rational numbers have Lebesgue measure zero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/142/1*gOOyUOjfazJkwzNgA7G8FA.png" /></figure><p>This example demonstrates an important difference between Riemann and Lebesgue integration.</p><h3>3. Exercise 2 : Numerical Computation of the Normal CDF</h3><h3>3.1 Mathematical definition</h3><p>The standard normal distribution is a continuous probability distribution with mean zero and standard deviation one.</p><p>Its probability density function (PDF) is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/170/1*IMHQF2yLc6xKyKFs6i9GDw.png" /></figure><p>The cumulative distribution function (CDF) gives the probability that a normally distributed random variable is less than or equal to a particular value z.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*W4rKxsXYOlRN08uXYy6UqQ.png" /></figure><p>The normal CDF is widely used in statistics, probability calculations, hypothesis testing, and machine learning.</p><h3>3.2 Why does the normal CDF have no elementary solution?</h3><p>The normal CDF cannot be expressed using elementary functions such as polynomials, exponentials, logarithms, and trigonometric functions.</p><p>This follows from the mathematical results associated with Liouville’s theorem on elementary antiderivatives.</p><p>For the Gaussian exponential, the relevant differential equation would require a rational function h(t) satisfying:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/157/1*ydXDrQavFmfWW7mUZ35nTw.png" /></figure><p>No rational function satisfies this condition. Consequently, the Gaussian density does not have an elementary antiderivative.</p><p>However, an exact representation is possible using a special mathematical function called the error function, or operatorname{erf}.</p><h3>3.3 Relationship between the normal CDF and error function</h3><p>The error function is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*GtGOpkM0Fxab_2KuvojTWw.png" /></figure><p>Using this function, the normal CDF can be expressed exactly as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*xf9bQ3ixVGK1LcLWFDBeXQ.png" /></figure><p>Although this provides an exact analytical representation, numerical computation is still necessary because the error function itself generally requires numerical algorithms for evaluation.</p><h3>3.4 Numerical methods</h3><p>I investigated two numerical approaches and used the error function as an analytical reference.</p><p>Method 1: Composite Simpson’s rule</p><p>Simpson’s rule approximates an integral using quadratic interpolation over successive pairs of subintervals.</p><p>The composite formula is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*UGkFBiKiol6lw5GK3dUx_w.png" /></figure><p>Where:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/100/1*BErR66mZTNhVkKk4KJ-hJA.png" /></figure><p>To simplify the normal CDF calculation, I used the symmetry property:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/170/1*dKPHNhMAJWAiQdTuJo8vng.png" /></figure><p>Therefore, it is sufficient to numerically integrate the normal density between zero and the absolute value of z.</p><p>Method 2: Taylor series expansion</p><p>The error function can also be represented using an infinite power series.</p><p>Integrating its corresponding expansion gives the following expression for the normal CDF:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*ekrUdxzCjORh-FrXzVCxzw.png" /></figure><p>This method allows the CDF to be approximated by calculating a finite number of terms.</p><p>For this homework, I used 50 terms.</p><p>Method 3: Error function implementation</p><p>Python provides an efficient implementation of the error function through the SciPy library.</p><p>It can be calculated using:</p><pre>from scipy.special import erf<br><br>def normal_cdf_erf(z):<br>    return 0.5 * (<br>        1 + erf(z / np.sqrt(2))<br>    )</pre><p>This method provides a convenient analytical reference for evaluating the numerical approaches.</p><h3>3.5 Python implementation</h3><p>The following code implements Simpson’s rule, the Taylor series, and the error function representation.</p><pre>import numpy as np<br>import math<br>from scipy.special import erf, ndtr<br><br><br># Method 1: Simpson&#39;s rule<br>def simpson_cdf(z, n=1000):<br><br>    if z == 0:<br>        return 0.5<br><br>    a = 0<br>    b = abs(z)<br>    h = (b - a) / n<br><br>    def pdf(t):<br>        return np.exp(-t**2 / 2) / np.sqrt(2*np.pi)<br><br>    total = pdf(a) + pdf(b)<br><br>    for i in range(1, n):<br>        x = a + i*h<br><br>        if i % 2 == 0:<br>            total += 2 * pdf(x)<br>        else:<br>            total += 4 * pdf(x)<br><br>    integral = total * h / 3<br><br>    if z &gt; 0:<br>        return 0.5 + integral<br>    else:<br>        return 0.5 - integral<br><br><br># Method 2: Taylor series<br>def taylor_cdf(z, terms=50):<br><br>    total = 0<br><br>    for k in range(terms):<br>        term = (<br>            (-1)**k * z**(2*k+1)<br>            / (<br>                2**k *<br>                (2*k+1) *<br>                math.factorial(k)<br>            )<br>        )<br><br>        total += term<br><br>    return 0.5 + total / np.sqrt(2*np.pi)<br><br><br># Method 3: Error function<br>def normal_cdf_erf(z):<br>    return 0.5 * (<br>        1 + erf(z / np.sqrt(2))<br>    )<br><br><br># Comparison<br>values = [-3, -2, -1, 0, 0.5, 1, 1.96, 3]<br><br>print(&quot;z | Reference | Simpson | Taylor&quot;)<br><br>for z in values:<br><br>    reference = ndtr(z)<br>    simpson = simpson_cdf(z)<br>    taylor = taylor_cdf(z)<br><br>    print(<br>        z,<br>        reference,<br>        simpson,<br>        taylor<br>    )</pre><h3>3.6 Numerical results</h3><p>The results were compared with SciPy’s ndtr function, which provides a trusted numerical reference for the standard normal CDF.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*-X17OW7PQF2TSgyvQcINqQ.png" /></figure><p>The results show that both numerical methods provide highly accurate approximations for the tested values.</p><h3>3.7 Accuracy and computational efficiency</h3><p>The two numerical methods have different computational characteristics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*oS0HQZc8JwxCxLMJS2d9mg.png" /></figure><p>Simpson’s rule has a computational cost proportional to the number of subintervals, while the Taylor series requires a number of calculations proportional to the number of terms.</p><p>For the tested values between -3 and 3, both methods produced results very close to the reference values.</p><p>The Taylor series is particularly convenient for understanding the mathematical structure of the CDF, whereas Simpson’s rule provides a more general numerical integration technique.</p><p>The error function implementation is preferable when a fast and reliable practical calculation is required.</p><h3>4. Overall Conclusion</h3><p>This Homework explored two important numerical concepts: Riemann and Lebesgue integration, and numerical computation of the standard normal CDF.</p><p>In Exercise 1, the numerical experiments demonstrated that both Riemann based and Lebesgue inspired approaches can approximate integrals accurately for different types of functions. However, their numerical behaviour depends on the function properties and the selected partitioning strategy. The Dirichlet function also demonstrated that Lebesgue integration can handle functions that are not Riemann integrable.</p><p>In Exercise 2, Simpson’s rule and the Taylor series provided accurate approximations of the normal CDF. The error function offered an exact analytical representation, while numerical methods made its practical evaluation possible.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6d24734cb1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Welford’s Recurrence Formulas: Online Mean, Variance and Sampling Distributions]]></title>
            <link>https://medium.com/@ramumadireddy1072/welfords-recurrence-formulas-online-mean-variance-and-sampling-distributions-0382e0637e9e?source=rss-f08e3b6f3210------2</link>
            <guid isPermaLink="false">https://medium.com/p/0382e0637e9e</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[RamuMadireddy]]></dc:creator>
            <pubDate>Thu, 05 Nov 2026 13:11:38 GMT</pubDate>
            <atom:updated>2026-11-05T13:11:38.354Z</atom:updated>
            <content:encoded><![CDATA[<p><em>An exploration of online statistics, simulation, and the effect of sample size on statistical estimates.</em></p><h3>1. Introduction</h3><p>In statistics, we often work with a collection of observations and want to calculate two important quantities: the mean and the variance.</p><p>The mean tells us the average value of our observations, while the variance tells us how spread out those observations are around the mean.</p><p>Normally, calculating these quantities requires collecting all the observations first. However, what happens when data arrives one observation at a time?</p><p>For example, imagine a system that records scores continuously. We may want to calculate the average score and its variance without storing every previous observation.</p><p>This is where Welford’s algorithm becomes useful.</p><p>Welford’s algorithm is an online method that calculates the mean and variance as new observations arrive. It updates the results using the previous values, without needing to recalculate everything from the beginning.</p><p>Its main advantages are:</p><ul><li>It processes data one observation at a time.</li><li>It does not need to store the entire dataset.</li><li>It is computationally efficient.</li><li>It is numerically more stable than some direct variance calculations.</li></ul><p>In this article, I will first derive Welford’s recurrence formulas and implement them in Python. Then, I will use these formulas in a simulation involving multiple hackers, each receiving a score between 0 and 10 for every system they attempt.</p><p>Finally, I will investigate how increasing the number of observations affects the sampling means and variances.</p><h3>2. Exercise 1 : Welford’s Recurrence Formulas</h3><h3>2.1 Understanding the mean</h3><p>Suppose we have a sequence of observations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/145/1*ZjW44nmacbU09KpzjAvYoA.png" /></figure><p>The arithmetic mean of these observations is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/1*Eu8lTiXBtv9oshEygBDO-Q.png" /></figure><p>Here:</p><ul><li>x_i represents an individual observation.</li><li>n represents the number of observations.</li><li>\bar{x}_n represents the mean of all observations.</li></ul><p>Our goal is to calculate the new mean using only the previous mean and the new observation.</p><h3>2.2 Deriving the recurrence formula for the mean</h3><p>We start with the definition:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*DhMrfr6RtIub_UjPPrEYGw.png" /></figure><p>We know that the sum of the first n-1 observations is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*xQE4-Mh_8rkv0HpJvVOGhw.png" /></figure><p>Substituting this into the previous equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/1*vfrJvGWl28F1mqlpYAcV5g.png" /></figure><p>Now we rearrange:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*kfoyLBFy3Z3Y1Cw2vTcJnw.png" /></figure><p>Therefore:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*bFHGh7NcjqtyAq4nQZe_0w.png" /></figure><p>This is Knuth’s recurrence formula for the mean.</p><p>What does this formula mean?</p><p>Instead of calculating the mean again using all previous observations, we simply:</p><ol><li>Calculate the difference between the new observation and the previous mean.</li><li>Divide that difference by the new number of observations.</li><li>Add the result to the previous mean.</li></ol><p>This gives us the updated mean.</p><h3>2.3 Deriving the Sum of Squares (SS)</h3><p>Now we want to calculate the variance.</p><p>First, we define the Sum of Squares, also called SS or M_{2,n}:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/1*8GZF0PLQDzEiqj4zFw_CnQ.png" /></figure><p>It measures the total squared distance of the observations from their current mean.</p><p>For the previous n-1 observations, we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*XjfnTOpUWPmRw588u6Cynw.png" /></figure><p>When a new observation arrives, the mean changes. Therefore, all the deviations must be measured relative to the new mean.</p><p>We can write:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*qVDiJ-XPlc6BM9DoTKVMIA.png" /></figure><p>Separate the last observation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*cMhvrvOKA567PqJTuf5q-w.png" /></figure><p>Using the previous mean and the fact that the sum of deviations from that mean is zero, the expression simplifies to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*Dko2k9NEE2mRLoAVDRk-gw.png" /></figure><p>From the mean recurrence, we know:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*GMtqhMwM_USD8V7O1zJ45w.png" /></figure><p>Substituting and simplifying gives:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*69iBxuzp3lGyrhUOv3SvTw.png" /></figure><p>This is the Welford recurrence formula for the Sum of Squares.</p><h3>2.4 Deriving the variance formula</h3><p>Once we have calculated the Sum of Squares, we can calculate the variance.</p><p>There are two common definitions, depending on what we want to measure.</p><p>Population variance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/123/1*jjik-wVQ_FF27TxzKmJDiA.png" /></figure><p>Unbiased sample variance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/137/1*0T4OR6o0MKAaKVJNT8Or6A.png" /></figure><p>The first divides by n, while the second divides by n-1.</p><p>In our work, we will use the sample variance because we want to estimate the theoretical variance of the probability distribution from each hacker’s observations.</p><h3>2.5 Summary of Welford’s formulas</h3><p>The complete algorithm can be summarized as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*7H3kUvE0O_d6ClUUNLnuvw.png" /></figure><p>Finally:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/127/1*LFbGbc7gikxX4NI-zcIGUg.png" /></figure><p>We only need to maintain three values:</p><ul><li>count: number of observations.</li><li>mean: current mean.</li><li>M2: current sum of squared deviations.</li></ul><h3>2.6 Python implementation</h3><p>Here is the implementation of Welford’s algorithm.</p><pre><br>def welford(data):<br>    count = 0<br>    mean = 0.0<br>    M2 = 0.0<br><br>    for x in data:<br>        count += 1<br>        delta = x - mean<br>        mean += delta / count<br>        M2 += delta * (x - mean)<br><br>    variance = M2 / (count - 1) if count &gt; 1 else 0.0<br><br>    return mean, variance</pre><p>The three core lines are:</p><pre>delta = x - mean<br>mean += delta / count<br>M2 += delta * (x - mean)</pre><p>These three operations update the mean and Sum of Squares every time a new observation arrives.</p><p>The algorithm requires only constant additional memory, regardless of how many observations are processed.</p><h3>2.7 Testing the algorithm with a simple example</h3><p>Let’s consider the following observations: [2,4,6,8,10]</p><p>We can calculate the running statistics after each observation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*DR32HoOli5sbFIK9a88P2A.png" /></figure><p>At the end:</p><p>mean = 6, M_2 = 40, S² = 10</p><p>Let’s verify it using Python:</p><pre><br>data = [2, 4, 6, 8, 10]<br><br>mean, variance = welford(data)<br><br>print(&quot;Mean:&quot;, mean)<br>print(&quot;Sample variance:&quot;, variance)</pre><p>Expected output:</p><pre>Mean: 6.0<br>Sample variance: 10.0</pre><p>This confirms that our implementation correctly calculates the mean and sample variance.</p><h3>3. Exercise 2 : Sampling Mean and Variance</h3><p>Now that we have implemented Welford’s algorithm, we can use it in a larger simulation.</p><p>The objective is to investigate whether the average sampling mean and average sampling variance approach the theoretical mean and variance of a chosen probability distribution.</p><h3>3.1 Defining the experiment</h3><p>Imagine that we have:</p><ul><li>m hackers.</li><li>n systems for each hacker.</li><li>One score for every attempted system.</li></ul><p>Each score is an integer between 0 and 10.</p><p>Each hacker therefore receives a sequence of n scores.</p><p>We will calculate the mean and sample variance of each hacker’s scores using Welford’s algorithm.</p><p>Then, we will compare the results across all hackers.</p><h3>3.2 Choosing a probability distribution</h3><p>For simplicity, I will use a discrete uniform distribution.</p><p>This means that every score between 0 and 10 has the same probability of occurring.</p><p>The possible values are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*zgaVoYgWoGTaMb0aWgO1dQ.png" /></figure><p>Each value has probability:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/187/1*UJiCHXzart6SZpJ7kQvUtw.png" /></figure><p>This is a convenient choice because all scores are equally likely.</p><h3>3.3 Calculating the theoretical mean</h3><p>The theoretical mean is calculated as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*TjY8GAhNbfhybwPCqgH_pw.png" /></figure><p>Substituting our distribution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*TlgonpFUfjI4T_IQ91lK_A.png" /></figure><p>Since the sum of the first ten positive integers is 55:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/82/1*ZpjMGkq9oQ0HoQch6jzzTg.png" /></figure><p>Therefore, the theoretical mean score is 5.</p><h3>3.4 Calculating the theoretical variance</h3><p>The theoretical variance is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*8L2XdtuP7-4v_V-dTHVszw.png" /></figure><p>First, calculate the expected squared value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*TEkC5bqU7m3BZxP_0eyUEw.png" /></figure><p>Our theoretical values are therefore:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*4d4nPz7Y7JxU4E4tBke0Wg.png" /></figure><p>These values will serve as our reference when evaluating the simulation.</p><h3>3.5 Running the simulation</h3><p>We will use: m = 10,000</p><p>This means we simulate 10,000 independent hackers.</p><p>Each hacker receives n scores.</p><p>We will repeat the experiment for:</p><p>n = {5, 10, 30, 100, 500}</p><p>For each hacker, we calculate:</p><ul><li>Their sampling mean.</li><li>Their sample variance.</li></ul><p>After calculating these quantities for all hackers, we calculate their averages.</p><p>The goal is to observe how the results change as the number of systems increases.</p><h3>4. Python implementation of the experiment</h3><p>We can now combine Welford’s algorithm with our probability distribution.</p><p>The following code performs the entire experiment.</p><h3>4.1 Generating scores and calculating statistics</h3><pre><br>import numpy as np<br><br>def welford(data):<br>    count = 0<br>    mean = 0.0<br>    M2 = 0.0<br><br>    for x in data:<br>        count += 1<br>        delta = x - mean<br>        mean += delta / count<br>        M2 += delta * (x - mean)<br><br>    variance = M2 / (count - 1) if count &gt; 1 else 0.0<br><br>    return mean, variance<br><br><br># Simulation parameters<br>m = 10000<br>n_values = [5, 10, 30, 100, 500]<br><br>rng = np.random.default_rng(20261105)<br><br>results = []<br><br>for n in n_values:<br><br>    hacker_means = []<br>    hacker_variances = []<br><br>    for hacker in range(m):<br><br>        # Generate n scores between 0 and 10<br>        scores = rng.integers(0, 11, size=n)<br><br>        # Calculate statistics using Welford<br>        mean, variance = welford(scores)<br><br>        hacker_means.append(mean)<br>        hacker_variances.append(variance)<br><br>    # Average results across all hackers<br>    avg_mean = np.mean(hacker_means)<br>    avg_variance = np.mean(hacker_variances)<br><br>    results.append([<br>        n,<br>        avg_mean,<br>        avg_variance<br>    ])<br><br>print(&quot;n | Average Mean | Average Variance&quot;)<br><br>for row in results:<br>    print(row)</pre><h3>4.2 Understanding the code</h3><p>Let’s understand the main parts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*3-mTr8EOJqXQq7XQtylXWA.png" /></figure><p>An important detail is that we generate a new sequence of scores for every hacker.</p><p>We also use a fixed random seed, so the experiment can be reproduced with the same software and random-number generator.</p><h3>5. Experimental results</h3><p>After running the simulation with 10,000 hackers, we obtain the following results.</p><h3>5.1 Comparing theoretical and experimental values</h3><p>The theoretical values are:</p><p>mean = 5, Variance = 10</p><p>Our experimental results are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*aqvZDE2xSWan56VoYAI5rw.png" /></figure><p>We can immediately notice that the experimental values are very close to the theoretical values.</p><p>For example, when each hacker attempts 500 systems, the average sampling mean is approximately 4.9988, while the theoretical mean is 5.</p><p>Similarly, the average sampling variance is approximately 9.9957, very close to the theoretical variance of 10.</p><p>Small differences are expected because we are working with randomly generated observations and a finite number of hackers.</p><h3>5.2 Visualizing the results</h3><p>The following graph compares the average sampling means and variances with their theoretical values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*yD4UAlYwP2erN9F2InH4jA.png" /></figure><p>The main observation is that both averages remain close to their theoretical values across all five sample sizes.</p><p>This is what we would expect from unbiased sampling estimators.</p><h3>5.3 Why are the results useful?</h3><p>The results demonstrate two important statistical properties.</p><p>First: The sample mean is an unbiased estimator of the theoretical mean.</p><p>For independent observations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/107/1*9a3UfrXkO089JvV0ZvSAMQ.png" /></figure><p>This means that if we repeatedly take samples and calculate their means, the average of those means approaches the true population mean.</p><p>Second: The sample variance is an unbiased estimator of the theoretical variance.</p><p>When we use the denominator n-1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/142/1*iwTubDKD4yWwCbrytCZrjA.png" /></figure><p>Therefore, the average of the sample variances across many independent samples approaches the theoretical variance.</p><p>This explains why our experimental averages are so close to 5 and 10.</p><h3>6. How does increasing n affect variability?</h3><p>This is one of the most important parts of the experiment.</p><p>So far, we have compared the average sampling means and variances with their theoretical values.</p><p>However, we also want to understand how much the estimates differ from one hacker to another.</p><p>For example, when two hackers each attempt five systems, their average scores may be quite different.</p><p>But if both attempt 500 systems, their average scores are generally much closer to each other.</p><p>This is explained by the concept of sampling variability.</p><h3>6.1 Variability of the sampling mean</h3><p>The variance of the sampling mean is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/177/1*J3DYfB9sRfkT_-jy6CSSaw.png" /></figure><p>Since our theoretical variance is 10:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/162/1*_2bKfL5Sz6Oz4dDu2rF93Q.png" /></figure><p>The standard deviation of the sampling mean, also called the standard error, is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/1*TiLnuCp-tFLm1EcQgs36EA.png" /></figure><p>Let’s calculate the theoretical standard error for different sample sizes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*xW9X7pOQoH3Q3S3OsV327A.png" /></figure><p>We can clearly see that the standard error decreases as the number of observations increases.</p><p>Standard error of the sampling mean</p><p>Theoretical standard error for the uniform distribution with variance 10.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*WF7W7v6qJkUiH7sexHjaJw.png" /></figure><p>This means that larger samples produce more precise estimates of the population mean.</p><h3>6.2 Variability of the sampling variance</h3><p>We can also investigate the variability of the sample variances across hackers.</p><p>Even though their average is close to the theoretical variance of 10, individual hackers can still obtain different variance estimates.</p><p>From our simulation, the observed standard deviations of the sample variances were:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*u2JK0lsmxzl20XPWmApcag.png" /></figure><p>These values show that the sample variances become less variable as the sample size increases.</p><p>For example, with only five systems, the standard deviation of the variance estimates is approximately 5.05.</p><p>With 500 systems, it falls to approximately 0.40.</p><p>This means that the variance estimates become more consistent across hackers when more observations are collected.</p><h3>6.3 Comparing both effects</h3><p>We can summarize the experiment with two important observations:</p><ul><li>The sampling means become more concentrated around the theoretical mean.</li><li>The sampling variances become more concentrated around the theoretical variance.</li></ul><p>Increasing n does not change the theoretical mean or variance of the original distribution. Instead, it improves the precision of our estimates.</p><p>This is an important distinction.</p><p>A larger sample does not necessarily produce a different population. It gives us more information about the same population.</p><h3>8. Python code for generating the graphs</h3><p>We can also generate the graphs ourselves using Matplotlib.</p><pre><br>import matplotlib.pyplot as plt<br><br>n = [5, 10, 30, 100, 500]<br><br>average_means = [4.9703, 4.9998, 4.9979, 5.0018, 4.9988]<br>average_variances = [9.9812, 10.0131, 10.0144, 9.9952, 9.9957]<br><br># First graph: theoretical vs experimental values<br>plt.figure(figsize=(9, 5))<br><br>plt.plot(n, average_means, marker=&#39;o&#39;,<br>         label=&#39;Average sampling mean&#39;)<br>plt.axhline(5, linestyle=&#39;--&#39;,<br>            label=&#39;Theoretical mean = 5&#39;)<br><br>plt.plot(n, average_variances, marker=&#39;s&#39;,<br>         label=&#39;Average sampling variance&#39;)<br>plt.axhline(10, linestyle=&#39;:&#39;,<br>            label=&#39;Theoretical variance = 10&#39;)<br><br>plt.xscale(&#39;log&#39;)<br>plt.xlabel(&#39;Number of systems (n)&#39;)<br>plt.ylabel(&#39;Value&#39;)<br>plt.title(&#39;Sampling estimates vs theoretical values&#39;)<br>plt.legend()<br>plt.grid()<br>plt.show()<br><br><br># Second graph: variability of estimates<br>mean_se = [1.4142, 1.0000, 0.5774, 0.3162, 0.1414]<br>variance_sd = [5.0453, 3.1529, 1.6589, 0.8896, 0.3977]<br><br>plt.figure(figsize=(9, 5))<br><br>plt.plot(n, mean_se, marker=&#39;o&#39;,<br>         label=&#39;Standard error of mean&#39;)<br>plt.plot(n, variance_sd, marker=&#39;s&#39;,<br>         label=&#39;SD of sample variances&#39;)<br><br>plt.xscale(&#39;log&#39;)<br>plt.yscale(&#39;log&#39;)<br>plt.xlabel(&#39;Number of systems (n)&#39;)<br>plt.ylabel(&#39;Standard deviation&#39;)<br>plt.title(&#39;Effect of sample size on variability&#39;)<br>plt.legend()<br>plt.grid()<br>plt.show()</pre><h3>9. Connection to inferential statistics</h3><p>Now we can understand why these results are important beyond this particular experiment.</p><p>Inferential statistics is the branch of statistics that allows us to use a sample to make conclusions about a larger population.</p><p>In many real situations, we cannot collect information about every individual or every possible observation.</p><p>Instead, we collect a sample and use it to estimate unknown population parameters.</p><p>Our experiment demonstrates three important ideas.</p><p>1. Estimation</p><p>The sample mean and sample variance can be used to estimate the theoretical mean and variance of a population.</p><p>In our experiment, the theoretical values were 5 and 10, and our experimental averages were very close to them.</p><p>2. Unbiased estimators</p><p>An estimator is unbiased when its expected value equals the parameter it estimates.</p><p>For independent observations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/115/1*lND0J4qwXjPpUZcYY5W2Vw.png" /></figure><p>This explains why averaging the estimates over many hackers produces values close to the theoretical parameters.</p><p>3. Sampling variability</p><p>Different samples from the same population do not necessarily produce identical estimates.</p><p>However, as the sample size increases, the estimates generally become more concentrated around their true population values.</p><p>This is important because it helps us understand how reliable our estimates are.</p><p>For example, if we want to estimate the average score of a large population, collecting more observations generally reduces the uncertainty associated with our estimate.</p><p>This is one of the fundamental ideas behind statistical inference.</p><h3>10. Conclusion</h3><p>In this homework, I studied Welford’s recurrence formulas and applied them to a simulation involving multiple hackers and their scores.</p><p>First, I derived the recurrence formula for the mean and the Sum of Squares. Using these two formulas, I implemented Welford’s algorithm in Python.</p><p>The implementation was particularly useful because it allowed me to calculate the mean and sample variance using only three main update operations, without storing all previous observations.</p><p>In the second part, I selected a discrete uniform distribution with scores between 0 and 10. Its theoretical mean was 5, and its theoretical variance was 10.</p><p>I then simulated 10,000 hackers for different numbers of attempted systems.</p><p>The experimental results showed that the average sampling means and variances were very close to their theoretical values.</p><p>Finally, I observed that increasing the number of systems reduced the variability of both the sampling means and the sampling variances.</p><p>The main conclusion is that larger samples generally provide more stable and precise statistical estimates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0382e0637e9e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Penetration Scores in Stochastic Systems: A Simulation Study of the LLN and CLT]]></title>
            <link>https://medium.com/@ramumadireddy1072/penetration-scores-in-stochastic-systems-a-simulation-study-of-the-lln-and-clt-996cce6fbc88?source=rss-f08e3b6f3210------2</link>
            <guid isPermaLink="false">https://medium.com/p/996cce6fbc88</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[RamuMadireddy]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 20:49:53 GMT</pubDate>
            <atom:updated>2026-10-28T20:49:53.939Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Introduction</h3><p>Stochastic processes provide a mathematical framework for studying systems whose outcomes depend on random events. In a penetration model, each step contributes a random increment to an aggregate score. Although individual increments are unpredictable, the total behavior may become more regular as the number of steps increases.</p><p>This homework considers n systems and m independent simulated trajectories representing possible realizations of the penetration process. We investigate two models: <strong>a Bernoulli model</strong>, in which each increment is either zero or one, and <strong>a Rademacher model</strong>, in which each increment is equally likely to be -1 or +1.</p><p>The main objectives are to examine how the total score, average score, and normalized total score behave as n increases. We use the <strong>Law of Large Numbers (LLN)</strong> to study the convergence of the average and the <strong>Central Limit Theorem (CLT)</strong> to investigate the distribution of the normalized Rademacher score.</p><p>An important distinction is that n represents the number of increments in each trajectory, whereas m represents the number of independent trajectories simulated for statistical analysis.</p><h3>2. Mathematical formulation</h3><p>Let X_1,X_2,….,X_n be independent and identically distributed random variables. The cumulative score after n steps is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/147/1*ivy_Tg0ygjfAh1bQJuohcg.png" /></figure><p>We study three quantities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/1*nRW2BQ27iCi77OzNLBKc_A.png" /></figure><p>The total score S_n measures the accumulated contribution of all increments. The average A_n measures the contribution per step. The normalized score Z_n rescales the total to examine its fluctuations on a scale proportional to the square root of n.</p><h3>2.1 Bernoulli model</h3><p>In the Bernoulli model,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*pFD320rDoAHdjQmlLT7WAA.png" /></figure><p>We choose p = 0.3 for the numerical experiment. The expectation and variance of each increment are</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/212/1*7wxLcsxjjVG7ZoWKHBkAQg.png" /></figure><p>By independence,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*p2DIEFp1xTFyq-P59kSbWQ.png" /></figure><p>The average therefore satisfies,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*4sVKMMlrI__LzBjwM5mUYg.png" /></figure><p>The average is expected to approach p as n grows, while the total score grows approximately linearly with n.</p><h3>2.2 Rademacher model</h3><p>In the Rademacher model,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/1*cvvovnrQet-AFjcG06PJTQ.png" /></figure><p>Each increment has zero expectation and unit variance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/170/1*3lFznHBzQVGTG_SYU-YLaQ.png" /></figure><p>Consequently,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/181/1*JUVPgspRgebYKfcXAwRn5Q.png" /></figure><p>For the average and normalized score, we obtain</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/185/1*unWl8sqbi0eS6KqGNUsllw.png" /></figure><p>and</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/1*5SZV2KOjTx4FP5dUayYLeQ.png" /></figure><p>These equations predict that the average converges toward zero, while the normalized total maintains a constant variance as the number of increments increases.</p><h3>3. Experimental design</h3><p>We simulate m = 5000 independent trajectories for each of the following system sizes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/1*I4UTATKNiuVPl_rnj6Z-Gw.png" /></figure><p>Each trajectory contains n independent increments. We use the same sample sizes and a fixed random seed for both models, making the results reproducible.</p><p>For each trajectory, we calculate the total, average, and normalized total. We then compare the empirical results with the theoretical expectations and variances.</p><p>The simulations illustrate the difference between two sources of variation: increasing n changes the behavior of each trajectory, whereas increasing m improves our estimates of the underlying distributions.</p><h3>4. Python implementation</h3><p>The following program generates the trajectories, calculates the empirical statistics, and produces four figures. It uses only NumPy and Matplotlib.</p><pre><br>import numpy as np<br>import matplotlib.pyplot as plt<br><br># Experiment settings<br>rng = np.random.default_rng(42)<br>p = 0.30<br>m = 5000<br>n_values = [10, 50, 100, 500, 1000]<br><br># Store simulation results for each model<br>results = {&quot;Bernoulli&quot;: {}, &quot;Rademacher&quot;: {}}<br><br>for n in n_values:<br>    # Each row represents one independent trajectory<br>    bernoulli = rng.binomial(1, p, size=(m, n))<br>    rademacher = rng.choice([-1, 1], size=(m, n))<br><br>    for name, increments in [<br>        (&quot;Bernoulli&quot;, bernoulli),<br>        (&quot;Rademacher&quot;, rademacher)<br>    ]:<br>        totals = increments.sum(axis=1)<br><br>        results[name][n] = {<br>            &quot;increments&quot;: increments,<br>            &quot;total&quot;: totals,<br>            &quot;average&quot;: totals / n,<br>            &quot;normalized&quot;: totals / np.sqrt(n)<br>        }<br><br># Figure 1: Example cumulative trajectories<br>fig, axes = plt.subplots(1, 2, figsize=(12, 4))<br><br>for ax, name in zip(axes, results):<br>    n = 100<br>    increments = results[name][n][&quot;increments&quot;]<br><br>    for j in range(5):<br>        path = np.cumsum(increments[j])<br>        ax.plot(np.arange(1, n + 1), path, alpha=0.8)<br><br>    ax.set_title(f&quot;{name}: cumulative trajectories&quot;)<br>    ax.set_xlabel(&quot;Number of steps, n&quot;)<br>    ax.set_ylabel(&quot;Cumulative score&quot;)<br>    ax.grid(alpha=0.3)<br><br>plt.tight_layout()<br>plt.show()<br><br># Figure 2: Empirical and theoretical variances<br>fig, axes = plt.subplots(1, 3, figsize=(15, 4))<br><br>for name in results:<br>    ns = np.array(n_values)<br><br>    var_total = [<br>        np.var(results[name][n][&quot;total&quot;])<br>        for n in ns<br>    ]<br>    var_average = [<br>        np.var(results[name][n][&quot;average&quot;])<br>        for n in ns<br>    ]<br>    var_normalized = [<br>        np.var(results[name][n][&quot;normalized&quot;])<br>        for n in ns<br>    ]<br><br>    if name == &quot;Bernoulli&quot;:<br>        v = p * (1 - p)<br>    else:<br>        v = 1.0<br><br>    axes[0].plot(ns, var_total, &quot;o-&quot;, label=name)<br>    axes[1].plot(ns, var_average, &quot;o-&quot;, label=name)<br>    axes[2].plot(ns, var_normalized, &quot;o-&quot;, label=name)<br><br>    axes[0].plot(ns, v * ns, &quot;--&quot;, alpha=0.6)<br>    axes[1].plot(ns, v / ns, &quot;--&quot;, alpha=0.6)<br>    axes[2].plot(ns, np.full(len(ns), v), &quot;--&quot;, alpha=0.6)<br><br>axes[0].set_title(&quot;Variance of total score&quot;)<br>axes[0].set_ylabel(&quot;Variance&quot;)<br>axes[1].set_title(&quot;Variance of average score&quot;)<br>axes[2].set_title(&quot;Variance of normalized score&quot;)<br><br>for ax in axes:<br>    ax.set_xlabel(&quot;Number of steps, n&quot;)<br>    ax.grid(alpha=0.3)<br>    ax.legend()<br><br>plt.tight_layout()<br>plt.show()<br><br># Figure 3: Normalized Rademacher scores and normal density<br>fig, axes = plt.subplots(1, 3, figsize=(14, 4))<br>x = np.linspace(-4, 4, 500)<br>normal_density = np.exp(-x**2 / 2) / np.sqrt(2 * np.pi)<br><br>for ax, n in zip(axes, [10, 100, 1000]):<br>    z = results[&quot;Rademacher&quot;][n][&quot;normalized&quot;]<br><br>    ax.hist(<br>        z, bins=40, density=True, alpha=0.65,<br>        edgecolor=&quot;white&quot;<br>    )<br>    ax.plot(x, normal_density, &quot;--&quot;, linewidth=2)<br>    ax.set_title(f&quot;Rademacher normalized score, n={n}&quot;)<br>    ax.set_xlabel(&quot;S_n / sqrt(n)&quot;)<br>    ax.set_ylabel(&quot;Density&quot;)<br>    ax.grid(alpha=0.2)<br><br>plt.tight_layout()<br>plt.show()<br><br># Figure 4: Distribution of average scores<br>fig, axes = plt.subplots(1, 2, figsize=(12, 4))<br><br>for ax, name in zip(axes, results):<br>    data = [<br>        results[name][n][&quot;average&quot;]<br>        for n in n_values<br>    ]<br><br>    ax.boxplot(data, tick_labels=[str(n) for n in n_values])<br>    ax.set_title(f&quot;{name}: average score&quot;)<br>    ax.set_xlabel(&quot;Number of steps, n&quot;)<br>    ax.set_ylabel(&quot;S_n / n&quot;)<br>    ax.grid(axis=&quot;y&quot;, alpha=0.3)<br><br>    target = p if name == &quot;Bernoulli&quot; else 0<br>    ax.axhline(target, linestyle=&quot;--&quot;, linewidth=2)<br><br>plt.tight_layout()<br>plt.show()<br><br># Print empirical statistics for comparison with theory<br>for name in results:<br>    print(f&quot;\n{name} model&quot;)<br><br>    for n in n_values:<br>        r = results[name][n]<br><br>        print(<br>            f&quot;n={n:4d} | &quot;<br>            f&quot;mean total={np.mean(r[&#39;total&#39;]):8.3f} | &quot;<br>            f&quot;var total={np.var(r[&#39;total&#39;]):8.3f} | &quot;<br>            f&quot;mean average={np.mean(r[&#39;average&#39;]):7.4f} | &quot;<br>            f&quot;var average={np.var(r[&#39;average&#39;]):8.5f} | &quot;<br>            f&quot;var normalized={np.var(r[&#39;normalized&#39;]):7.4f}&quot;<br>        )</pre><h3>5. Results and statistical interpretation</h3><p>The following are the theoretical predictions that the simulation should illustrate. The numerical output from the program should be used to confirm how closely the empirical results agree with them.</p><h3>5.1 Total score</h3><p>For the Bernoulli model,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/1*k2-F6NXNIj14nap_ENQbZw.png" /></figure><p>For the Rademacher model,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/183/1*Q_PqbEgBW4VsjNbqwXW2zw.png" /></figure><p>The Bernoulli total increases approximately linearly because positive increments occur with probability 0.3. The Rademacher total fluctuates around zero because positive and negative increments have equal probabilities.</p><p>In both cases, the variance increases with n. Thus, the total score becomes larger in scale even when its expected value is zero. For the Rademacher model, the standard deviation is sqrt n, rather than n.</p><h3>5.2 Average score and the Law of Large Numbers</h3><p>The LLN states that, for i.i.d. increments with finite expectation,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/148/1*NQKclylTE-dK8j_4LjS0lw.png" /></figure><p>Here, convergence in probability means that, for every epsilon&gt;0,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*ncgcB1prz2ROkyOKh-O2aA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*AaFzN8WTgE4H68COMCTuRA.png" /></figure><p>For the Bernoulli model, the average converges in probability to p=0.3. For the Rademacher model, it converges in probability to zero.</p><p>The reason is that the variance of the average decreases as 1/n. Chebyshev’s inequality makes this relationship explicit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*72uLfPWbPvnE7IGsBQ5tBg.png" /></figure><p>As n increases, the probability of a substantial deviation from the expected average decreases. In the boxplots, this should appear as progressively narrower distributions centered around 0.3 for Bernoulli and zero for Rademacher.</p><h3>5.3 Normalized total and the Central Limit Theorem</h3><p>The CLT states that, when the increments have finite, positive variance,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*HQevqlXnrZHdvKppvcIKAA.png" /></figure><p>This means that the distribution of the normalized total approaches the standard normal distribution as n increases.</p><p>The histograms in figure compare the simulated normalized scores with the standard normal density. For small n, the distribution is discrete because the score can only take specific values. As n increases, the discrete distribution more closely resembles the smooth bell-shaped normal curve.</p><p>The normalized score has variance one for every n, not just in the limit. This follows directly from</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*nKO6KQhxRA4FbHizcfVs-A.png" /></figure><p>The CLT concerns convergence of the distribution, rather than a reduction in the variance of this normalized quantity.</p><h3>5.4 Comparison of the three quantities</h3><p>The theoretical variances summarize the main findings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*JvC_himgxO0JEZpFIQX28g.png" /></figure><p>The normalized Bernoulli total also has constant variance, but its mean is 0.3\sqrt n, which increases with n. Consequently, it does not converge to a standard normal distribution without centering.</p><p>Its centered and standardized form is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*V08BPQo4TMw3zVEuvXQhfA.png" /></figure><p>This comparison shows why normalization must be chosen according to the property being studied. Dividing by n stabilizes the average, while dividing by (sqrt n) preserves the scale of random fluctuations.</p><h3>6. Interpretation in terms of systems and attackers</h3><p>The model can be interpreted by considering each trajectory as the experience of one attacker across n systems. Each increment represents that attacker’s score contribution at one step. Under this interpretation, m attackers provide m independent trajectories.</p><p>Effect of the number of systems, n. As the number of systems increases, each attacker’s cumulative score incorporates more random increments. In the Bernoulli model, the expected total grows proportionally to the number of systems. In the Rademacher model, the expected total remains zero, although the typical size of fluctuations increases.</p><p>Effect on the average score. A larger system sample makes the average contribution more predictable. The Bernoulli average approaches 0.3 in our illustrative model, while the Rademacher average approaches zero. This is a statistical statement about the model, not a guarantee about real systems.</p><p>Effect of the number of attackers, m. Increasing the number of independently simulated attackers improves the precision of empirical estimates. It allows us to estimate means, variances, and distributions more reliably. However, increasing m does not change the theoretical distribution of an individual trajectory when n and the increment model remain fixed.</p><p>If we instead want to calculate the combined score across all attackers, we can define</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/1*HAqbA_VT1HF4vtUGOvCoMQ.png" /></figure><p>where S_n^(j) denotes the score of attacker j. Assuming independence across attackers,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*eK-ClBbbmqevVN4KNuI6GA.png" /></figure><p>This aggregate score is different from the individual trajectory score S_n. Making that distinction prevents us from incorrectly multiplying the individual score or its variance by m.</p><p>Finally, the model assumes independent, identically distributed increments. Real systems may have dependencies, different vulnerabilities, or attackers with different capabilities. Therefore, the model illustrates general statistical principles rather than predicting actual penetration outcomes.</p><h3>Conclusion</h3><p>This homework shows how the total, average, and normalized penetration scores behave as the number of systems n increases. The Law of Large Numbers explains why the average score converges to its expected value. The Central Limit Theorem shows that the normalized Rademacher score approaches a standard normal distribution. Increasing the number of attackers m improves the reliability of the simulation results. Overall, these results demonstrate how probability theory helps explain random outcomes in large systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=996cce6fbc88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When Encryption Becomes Predictable: An Experimental Study of Caesar Ciphers and Elliptic Curves]]></title>
            <link>https://medium.com/@ramumadireddy1072/when-encryption-becomes-predictable-an-experimental-study-of-caesar-ciphers-and-elliptic-curves-ea0d72ae65ad?source=rss-f08e3b6f3210------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea0d72ae65ad</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[RamuMadireddy]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 03:52:47 GMT</pubDate>
            <atom:updated>2026-10-22T03:52:47.481Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Introduction</h3><p>Cryptography protects information by transforming readable messages into representations that should be understandable only to authorized recipients. The strength of this protection depends not only on the mathematical operations involved, but also on how keys are selected, how messages are processed, and what information an attacker can exploit.</p><p>This homework 3 compares two encryption systems with very different security foundations: the Caesar cipher, a classical substitution cipher, and a toy public key encryption scheme based on elliptic curve cryptography (ECC).</p><p><strong>The Caesar cipher</strong> shifts each letter by a fixed number of positions in the alphabet. Because its key space is small and natural language text has a non-uniform letter distribution, an attacker can try every possible shift or estimate the key statistically. The effectiveness of these methods depends partly on the amount and characteristics of the available ciphertext.</p><p><strong>Elliptic curve cryptography</strong> instead relies on arithmetic over points on an elliptic curve. In a public key system, the public key is derived from a private scalar, and recovering that scalar from the public key is intended to be computationally infeasible when secure parameters are used. However, restricting the private key to a small range can undermine this protection, even if the underlying curve is otherwise well chosen.</p><p>The work is examine these weaknesses from two perspectives. First, letter frequency analysis is used to estimate Caesar cipher keys from ciphertexts of different lengths. Second, a restricted key search is used to investigate how a small private key space affects a toy ECC scheme.</p><p>The goal is to compare the assumptions, methods, and limitations of these attacks, and to distinguish vulnerabilities caused by an intentionally restricted key space from the security properties of properly configured cryptography.</p><h3>2. Experimental design and methodology</h3><p>We will use one shared plaintext for the encryption comparison and separate experiments for the two attacks. The methods follow the standard approach of comparing candidate Caesar decryptions with expected English letter frequencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*dxQwhIRY3dJlwhaNsbk0Zw.png" /></figure><p>For the ECC message demonstration, we’ll use a clearly labeled educational ECIES style construction on secp256k1, using ephemeral elliptic curve Diffie–Hellman and a SHA 256 derived XOR stream. This supplies an explicit encryption or decryption procedure without pretending that the key generator you sent already implements encryption. It is a teaching construction, not production secure ECIES.</p><h3>3. Experiment A : Encrypting and decrypting the same message</h3><p>We will use the following plaintext in both demonstrations:</p><h3>3.1 Caesar cipher</h3><p>The Caesar cipher operates on alphabet positions. If x is the position of a plaintext letter and k is the secret shift, encryption and decryption are</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/1*eOmt45teWzfwzBjXLS292A.png" /></figure><p>For example, a shift of 3 maps A to D, B to E, and so on. A shift of 26 is equivalent to a shift of zero, so there are 25 nontrivial keys.</p><pre>def caesar_encrypt(text, shift):<br>    result = []<br><br>    for char in text:<br>        if char.isalpha() and char.isascii():<br>            base = ord(&#39;A&#39;) if char.isupper() else ord(&#39;a&#39;)<br>            result.append(<br>                chr((ord(char) - base + shift) % 26 + base)<br>            )<br>        else:<br>            result.append(char)<br><br>    return &#39;&#39;.join(result)<br><br><br>def caesar_decrypt(ciphertext, shift):<br>    return caesar_encrypt(ciphertext, -shift)<br><br><br>message = &quot;STATISTICS MAKES HIDDEN PATTERNS VISIBLE&quot;<br>shift = 7<br><br>ciphertext = caesar_encrypt(message, shift)<br>recovered = caesar_decrypt(ciphertext, shift)<br><br>print(&quot;Original:   &quot;, message)<br>print(&quot;Ciphertext: &quot;, ciphertext)<br>print(&quot;Recovered:  &quot;, recovered)<br>print(&quot;Correct:    &quot;, recovered == message)</pre><p>Expected verification: Correct: True.</p><p>The procedure is reversible because decryption applies the opposite shift. However, the small key space means an attacker can test every candidate shift without knowing the original key.</p><h3>3.2 ECC style message encryption</h3><p>The following implementation uses secp256k1 point arithmetic and a simplified ECIES style construction. Your supplied HTML code uses a different, much smaller curve, so this implementation is an extension rather than a direct reuse of that HTML program.</p><p>The scheme works as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*vyypiWBIXrggpR47irHEpQ.png" /></figure><p>This is an educational construction, not production secure ECIES: it does not authenticate ciphertexts, and its custom key derivation and encryption design should not be used to protect real data. The secp256k1 parameters are specified , and NIST discusses elliptic-curve domain paramateres are specified.</p><p>Here is the complete point arithmetic and encryption implementation. It uses only Python’s standard library.</p><pre>import hashlib<br>import secrets<br><br># secp256k1 domain parameters<br>P = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F<br><br>N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141<br><br>G = (<br>    0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798,<br>    0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8,<br>)<br><br># None represents the point at infinity.<br><br><br>def point_add(A, B):<br>    if A is None:<br>        return B<br>    if B is None:<br>        return A<br><br>    x1, y1 = A<br>    x2, y2 = B<br><br>    if x1 == x2 and (y1 + y2) % P == 0:<br>        return None<br><br>    if A == B:<br>        slope = (3 * x1 * x1) * pow(2 * y1, -1, P) % P<br>    else:<br>        slope = (y2 - y1) * pow((x2 - x1) % P, -1, P) % P<br><br>    x3 = (slope * slope - x1 - x2) % P<br>    y3 = (slope * (x1 - x3) - y1) % P<br><br>    return x3, y3<br><br><br>def scalar_mult(k, point=G):<br>    result = None<br>    addend = point<br><br>    while k &gt; 0:<br>        if k &amp; 1:<br>            result = point_add(result, addend)<br><br>        addend = point_add(addend, addend)<br>        k &gt;&gt;= 1<br><br>    return result<br><br><br>def derive_stream(shared_x, length):<br>    seed = shared_x.to_bytes(32, &quot;big&quot;)<br>    output = b&quot;&quot;<br>    counter = 0<br><br>    while len(output) &lt; length:<br>        block = hashlib.sha256(<br>            seed + counter.to_bytes(4, &quot;big&quot;)<br>        ).digest()<br><br>        output += block<br>        counter += 1<br><br>    return output[:length]<br><br><br>def xor_bytes(first, second):<br>    return bytes(a ^ b for a, b in zip(first, second))<br><br><br>def ecc_encrypt(message, public_key, ephemeral_scalar=None):<br>    if ephemeral_scalar is None:<br>        ephemeral_scalar = secrets.randbelow(N - 1) + 1<br><br>    c1 = scalar_mult(ephemeral_scalar)<br>    shared_point = scalar_mult(ephemeral_scalar, public_key)<br><br>    stream = derive_stream(shared_point[0], len(message))<br>    encrypted = xor_bytes(message, stream)<br><br>    return c1, encrypted<br><br><br>def ecc_decrypt(c1, ciphertext, private_key):<br>    shared_point = scalar_mult(private_key, c1)<br>    stream = derive_stream(shared_point[0], len(ciphertext))<br><br>    return xor_bytes(ciphertext, stream)<br><br><br># Demonstration<br>message = b&quot;STATISTICS MAKES HIDDEN PATTERNS VISIBLE&quot;<br><br>private_key = 1739<br>public_key = scalar_mult(private_key)<br><br>c1, encrypted = ecc_encrypt(message, public_key)<br>recovered = ecc_decrypt(c1, encrypted, private_key)<br><br>print(&quot;Public key:&quot;, public_key)<br>print(&quot;Ciphertext (hex):&quot;, encrypted.hex())<br>print(&quot;Recovered:&quot;, recovered.decode(&quot;utf-8&quot;))<br>print(&quot;Correct:&quot;, recovered == message)</pre><p>The private key is deliberately selected for the later restricted key experiment. In a properly configured system, private key generation must use the appropriate full size range and secure cryptographic procedures.</p><h3>4. Experiment B : Statistical cryptanalysis of the Caesar cipher</h3><p>The Caesar cipher preserves the overall letter frequency pattern of its plaintext, although each letter is shifted to a different position. Frequency analysis exploits this property by comparing observed letter counts against the expected distribution of English.</p><h3>4.1 The chi-square method</h3><p>For each possible shift k, decrypt the ciphertext and calculate</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*32HxLznRTJp0oVuHTluSSw.png" /></figure><p>where O_i is the observed count of letter i, and E_i is the expected count under the English language model.</p><p>The algorithm selects the shift with the smallest score. This evaluates all 26 letters rather than relying only on the most frequent ciphertext letter.</p><pre>import string<br><br>LETTERS = string.ascii_uppercase<br><br>ENGLISH_FREQ = [<br>    0.08167, 0.01492, 0.02782, 0.04253, 0.12702,<br>    0.02228, 0.02015, 0.06094, 0.06966, 0.00153,<br>    0.00772, 0.04025, 0.02406, 0.06749, 0.07507,<br>    0.01929, 0.00095, 0.05987, 0.06327, 0.09056,<br>    0.02758, 0.00978, 0.02360, 0.00150, 0.01974,<br>    0.00074<br>]<br><br><br>def chi_square(text):<br>    letters = [<br>        char.upper()<br>        for char in text<br>        if char.upper() in LETTERS<br>    ]<br><br>    if not letters:<br>        return float(&quot;inf&quot;)<br><br>    counts = [0] * 26<br><br>    for char in letters:<br>        counts[ord(char) - ord(&quot;A&quot;)] += 1<br><br>    total = len(letters)<br>    score = 0.0<br><br>    for i in range(26):<br>        expected = total * ENGLISH_FREQ[i]<br>        observed = counts[i]<br><br>        if expected &gt; 0:<br>            score += (observed - expected) ** 2 / expected<br><br>    return score<br><br><br>def frequency_attack(ciphertext):<br>    scores = [<br>        chi_square(caesar_decrypt(ciphertext, shift))<br>        for shift in range(26)<br>    ]<br><br>    best_shift = min(range(26), key=lambda k: scores[k])<br><br>    return (<br>        best_shift,<br>        caesar_decrypt(ciphertext, best_shift),<br>        scores[best_shift]<br>    )<br><br><br>ciphertext = caesar_encrypt(message.decode(), 7)<br>guess, plaintext_guess, score = frequency_attack(ciphertext)<br><br>print(&quot;Actual shift:&quot;, 7)<br>print(&quot;Estimated shift:&quot;, guess)<br>print(&quot;Recovered text:&quot;, plaintext_guess)<br>print(&quot;Chi-square score:&quot;, round(score, 3))<br>print(&quot;Correct key:&quot;, guess == 7)</pre><p>Important: This final example uses the short demonstration message. It shows the algorithm, but a short message does not provide enough evidence to judge statistical reliability. The proper evaluation uses longer passages from a known language corpus.</p><h3>4.2 Testing different ciphertext lengths</h3><p>Save a substantial English language text in a file named english_corpus.txt. For reproducibility, use a public domain corpus or another text you are permitted to use, and document its source.</p><p>The following experiment tests six lengths with 100 randomized trials per length. It samples different passages and shifts, then measures the fraction of correctly recovered keys.</p><pre>import random<br>from pathlib import Path<br><br>random.seed(2026)<br><br>corpus = Path(&quot;english_corpus.txt&quot;).read_text(<br>    encoding=&quot;utf-8&quot;<br>)<br><br>corpus = &quot;&quot;.join(<br>    char for char in corpus<br>    if char.isascii() and (char.isalpha() or char.isspace())<br>)<br><br>if len(corpus) &lt; 2000:<br>    raise ValueError(<br>        &quot;Use a substantially larger English corpus for the experiment.&quot;<br>    )<br><br><br>def sample_passage(text, start, length):<br>    # Select a passage without wrapping around the corpus.<br>    end = min(start + length, len(text))<br>    passage = text[start:end]<br><br>    if len(passage) &lt; length:<br>        passage += text[:length - len(passage)]<br><br>    return passage<br><br><br>lengths = [40, 80, 160, 320, 640, 1280]<br>trials_per_length = 100<br><br>print(&quot;Length | Successful attacks | Accuracy&quot;)<br><br>for length in lengths:<br>    successes = 0<br><br>    for _ in range(trials_per_length):<br>        start = random.randrange(len(corpus))<br>        passage = sample_passage(corpus, start, length)<br><br>        actual_shift = random.randint(1, 25)<br>        ciphertext = caesar_encrypt(passage, actual_shift)<br><br>        estimated_shift, _, _ = frequency_attack(ciphertext)<br><br>        if estimated_shift == actual_shift:<br>            successes += 1<br><br>    accuracy = successes / trials_per_length<br><br>    print(<br>        f&quot;{length:6d} | &quot;<br>        f&quot;{successes:18d} | &quot;<br>        f&quot;{accuracy:.1%}&quot;<br>    )</pre><p>A plot can then be created from the recorded accuracies. The expected pattern is that frequency analysis often becomes more reliable as the sample grows, but this is not guaranteed for every passage or language. The precise outcome depends on the corpus and the method.</p><h3>5. Experiment C : Recovering a restricted ECC private key</h3><p>The public key is computed as</p><p>Q = dG,</p><p>where d is the private scalar and G is the base point.</p><p>If the private key is known to lie between 1 and 5,000, an attacker can enumerate every candidate d’, compute d’G, and compare it with the observed public key Q.</p><pre>KEY_LIMIT = 5000<br><br># Demonstration key from the ECC experiment<br>private_key = 1739<br>public_key = scalar_mult(private_key)<br><br>recovered_key = None<br>candidates_tested = 0<br><br>for candidate in range(1, KEY_LIMIT + 1):<br>    candidates_tested += 1<br><br>    if scalar_mult(candidate) == public_key:<br>        recovered_key = candidate<br>        break<br><br>print(&quot;Original private key:&quot;, private_key)<br>print(&quot;Recovered private key:&quot;, recovered_key)<br>print(&quot;Candidates tested:&quot;, candidates_tested)<br>print(&quot;Key recovered correctly:&quot;, recovered_key == private_key)<br><br># Confirm that the recovered key decrypts the message.<br>if recovered_key is not None:<br>    recovered_message = ecc_decrypt(<br>        c1, encrypted, recovered_key<br>    )<br>    print(&quot;Recovered message:&quot;, recovered_message.decode())</pre><h3>Why this attack works</h3><p>The attack does not exploit the statistical properties of the encrypted message. It uses the fact that the private key belongs to a small, known set.</p><p>For a full secp256k1 key space, the private scalar is selected from a range containing roughly 2^{256} possibilities, subject to the curve’s group order. A search over the entire range would be infeasible with ordinary computing resources. NIST’s domain parameter guidance recognizes secp256k1 as a curve supporting approximately 128-bit security strength.</p><h3>6. Comparing the encryption systems and their attacks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*tjRPiZeUiyKIpK55sqR2KQ.png" /></figure><p>The attacks differ in what makes them effective. The Caesar attack exploits information leaked by the structure of natural language. The ECC attack exploits an implementation constraint on the private key.</p><h3>7. Limitations and discussion</h3><p>Several limitations must be considered when interpreting the experiments.</p><p>First, English letter frequencies vary by writing style, subject, and sample size. Very short passages may not resemble the reference distribution, and the chi-square method may choose an incorrect shift. A more advanced method could compare n-gram frequencies common pairs or groups of letters or use a likelihood model trained on a larger corpus.</p><p>Second, the ECC demonstration uses a simplified, unauthenticated encryption construction for teaching purposes. It is not a replacement for a reviewed encryption library or standard ECIES implementation. The point arithmetic is also implemented directly in Python for transparency rather than constant time operation.</p><p>Third, the restricted key attack assumes that the public key is known and that the private key is guaranteed to lie within the tested interval. If either assumption changes, the attack’s feasibility changes too. In particular, searching the full secp256k1 private key space is not a practical extension of the same experiment.</p><p>Finally, these experiments do not establish that ECC is inherently unbreakable. They demonstrate that cryptographic security depends on appropriate parameters, correct implementation, and sound key management, as well as on the underlying mathematical problem.</p><h3>8. Conclusion</h3><p>This Homework 2 (3) compares a classical substitution cipher with a toy elliptic curve encryption construction using two different forms of cryptanalysis.</p><p>The Caesar experiment demonstrates how statistical properties of natural language text can reveal a key, and how the accuracy of that approach depends on the ciphertext and reference corpus. The ECC experiment shows how a restricted private key space permits direct enumeration even when the underlying curve is secp256k1.</p><p>The central result is that the attacks exploit different weaknesses. Caesar cryptanalysis benefits from a small key space and recognizable language patterns. The ECC attack benefits from an artificially small range of private keys. Neither experiment justifies treating a classroom construction as secure for real applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea0d72ae65ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Randomness to an Ethereum Address: A Statistical Study]]></title>
            <link>https://medium.com/@ramumadireddy1072/from-randomness-to-an-ethereum-address-a-statistical-study-70d6b7f54e3f?source=rss-f08e3b6f3210------2</link>
            <guid isPermaLink="false">https://medium.com/p/70d6b7f54e3f</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[cyrptocurrency]]></category>
            <dc:creator><![CDATA[RamuMadireddy]]></dc:creator>
            <pubDate>Thu, 15 Oct 2026 06:02:37 GMT</pubDate>
            <atom:updated>2026-10-15T06:02:37.013Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Introduction</h3><p>Cryptocurrency wallets rely on cryptographic methods to generate and manage digital identities. An Ethereum address may look like a simple string of hexadecimal characters, but generating it involves several steps, including random number generation, key derivation, elliptic-curve cryptography, and hashing.</p><p>In this work, I study the process of generating an Ethereum address from a statistical perspective. In particular, I examine how randomness is represented, how cryptographic hash functions behave when their inputs change, and how statistical methods can help evaluate the properties of generated addresses.</p><p>The main objective is to connect the theoretical concepts of cryptography with practical statistical experiments. Rather than assuming that a system is secure because its output looks random, I investigate which properties can be measured and what conclusions can reasonably be drawn from the results.</p><p>The project focuses on three questions:</p><ol><li>How does randomness contribute to the security of an Ethereum wallet?</li><li>What statistical behavior can be observed in cryptographic hash outputs?</li><li>How effectively can checksums detect errors in mnemonic phrases and Ethereum addresses?</li></ol><h3>2. The Ethereum Wallet-Generation Pipeline</h3><p>An Ethereum wallet address is generated through a sequence of cryptographic operations. Each operation has a specific purpose, from representing random information in a human-readable form to producing a public address.</p><p>The main stages are:</p><p><strong>Entropy → Mnemonic → Seed → Private Key → Public Key → Ethereum Address</strong></p><p>These stages are connected, but they do not perform the same function. Entropy provides the initial randomness, the mnemonic makes recovery easier for humans, and the seed allows a wallet to derive cryptographic keys deterministically. The public key and hashing operations are then used to calculate the Ethereum address.</p><h3>2.1 Entropy: The Starting Point</h3><p>Entropy is the initial random information used to create a wallet. In a typical BIP-39 wallet, the initial entropy contains between 128 and 256 bits.</p><p>A bit is a binary digit that can have one of two values: 0 or 1. Therefore, a sequence of 128 bits has 2^128 possible combinations.</p><p>If all combinations are equally likely, the initial entropy has 128 bits of Shannon entropy. This represents the maximum uncertainty associated with the randomly generated value.</p><p>However, the number of possible combinations alone does not guarantee security. If the random-number generator is predictable, an attacker may be able to guess the initial value despite its length.</p><p>For this reason, the quality of the original randomness is one of the most important factors in wallet security.</p><h3>2.2 From Entropy to a Mnemonic</h3><p>BIP-39 defines how binary entropy is converted into a mnemonic phrase consisting of familiar words.</p><p>First, a checksum is calculated from the entropy using SHA-256. A portion of this checksum is appended to the original entropy. The resulting sequence is then divided into groups of 11 bits, with each group corresponding to a word in a predefined list of 2,048 words.</p><p>For example, 128 bits of initial entropy produce a 12 word mnemonic. The mnemonic makes it easier for a user to back up and recover a wallet, but it does not replace the need for secure randomness.</p><h3>2.3 From the Seed to an Ethereum Address</h3><p>The mnemonic is used to derive a binary seed. BIP-32 can then use this seed to generate a hierarchy of keys, while BIP-44 defines a standard structure for organizing those keys.</p><p>A private key is used to calculate its corresponding public key through elliptic-curve cryptography. Ethereum then applies Keccak-256 to the appropriate public-key representation and takes the final 20 bytes of the hash to obtain the address.</p><p>Finally, EIP-55 can add a mixed-case checksum representation to help users detect certain address-entry errors.</p><p>The pipeline illustrates an important distinction: some operations encode or organize information, while others perform cryptographic transformations. Understanding these differences will help interpret the statistical experiments in the following sections.</p><h3>3. The Role of Each Standard and Cryptographic Primitive</h3><p>The Ethereum wallet generation process combines several technologies because each one solves a different problem. Some standards organize secret information and derive keys, while others provide public key cryptography, hashing, or error detection.</p><p>Understanding these distinctions is essential for understanding the complete pipeline.</p><h3>3.1 BIP-39: Mnemonic and Seed Generation</h3><p>BIP-39 defines how a sequence of random bits is represented as a mnemonic sentence and how that sentence is converted into a seed.</p><p>The mnemonic makes wallet backup and recovery easier for users. The seed provides the input used by hierarchical deterministic wallet systems to derive cryptographic keys.</p><p>BIP-39 therefore connects human-readable information with the binary data used by cryptographic software.</p><h3>3.2 BIP-32: Hierarchical Deterministic Key Derivation</h3><p>BIP-32 defines hierarchical deterministic (HD) wallets. An HD wallet can derive a tree of related keys from a single master seed.</p><p>This makes it possible to generate multiple accounts and addresses without separately backing up every private key.</p><p>Key derivation is different from key generation. Key generation creates a new cryptographic key, while deterministic key derivation calculates a key from existing secret material and a specified derivation procedure.</p><h3>3.3 BIP-44: Standard Derivation Paths</h3><p>BIP-44 builds on the hierarchical key structure defined by BIP-32. It specifies a common organization for accounts and addresses through a derivation path.</p><p>A commonly used Ethereum path is:</p><p>m/44&#39;/60&#39;/0&#39;/0/0</p><p>The path identifies the purpose, coin type, account, address chain, and address index. The apostrophe indicates hardened derivation.</p><p>BIP-44 does not replace BIP-32. Instead, it defines a convention for organizing keys within the hierarchical structure.</p><h3>3.4 secp256k1: Public-Key Cryptography</h3><p>Ethereum uses the secp256k1 elliptic curve for externally owned account keys.</p><p>A private key is a secret integer, while the corresponding public key is calculated through elliptic curve point multiplication. The public key can be shared, but the private key must remain secret.</p><p>This mathematical relationship supports digital signatures. A wallet uses the private key to authorize a transaction, and other participants can verify the signature using the associated public key.</p><p>Public key cryptography is therefore different from hashing: it establishes a relationship between private and public keys and supports authentication.</p><h3>3.5 Keccak-256: Hashing</h3><p>Keccak-256 is the hash function used in Ethereum address derivation.</p><p>A cryptographic hash maps input data to a fixed length output. Ethereum calculates the Keccak-256 hash of the appropriate public key bytes and takes the final 20 bytes to form the address.</p><p>Hashing is not encryption. It does not provide a secret key for recovering the original input.</p><p>It is also important to distinguish Ethereum’s Keccak-256 from standardized SHA3–256. Although they share the Keccak design, their padding conventions differ, so their outputs are not interchangeable.</p><h3>3.6 EIP-55: Checksum Encoding</h3><p>EIP-55 defines a mixed case representation for Ethereum addresses. The capitalization of hexadecimal letters is determined by hashing the lowercase address.</p><p>This representation helps detect many accidental typing errors. It does not change the underlying address bytes or create a new cryptographic key.</p><p>A checksum is also not the same as encryption or digital signature verification. Its purpose is to provide an error detection mechanism when addresses are displayed or entered.</p><h3>4.1 The Avalanche Effect</h3><p>The Hamming distance is the number of bit positions at which two hash outputs differ.</p><p>For two 256-bit hash outputs:</p><p>Hamming distance = number of differing bit positions</p><p>The distance can range from 0 to 256.</p><p>Under an idealized model, each output bit has a 50% probability of differing between the two hashes. Therefore:</p><p>Expected Hamming distance = 256 × 0.5 = 128 bits</p><p>This is an expected value, not a requirement that every pair of hashes must differ in exactly 128 bits.</p><h3>4.2 Statistical Distribution of Ethereum Address Bits</h3><p>Suppose we generate N Ethereum addresses and examine one particular bit position.</p><p>Let:</p><ul><li>N = total number of addresses sampled.</li><li>X = number of addresses where the selected bit is 1.</li><li>p̂ = observed proportion of ones.</li></ul><p>The observed proportion is:</p><p>p̂ = X / N</p><p>Under the idealized assumption that the bit is equally likely to be 0 or 1, the expected proportion is 0.5.</p><p>The standard error is:</p><p>Standard error = √[0.5 × (1 − 0.5) / N]</p><p>This simplifies to:</p><p>Standard error = 0.5 / √N</p><p>For example, if N = 10,000 addresses:</p><p>Standard error = 0.5 / √10,000 = 0.005</p><p>This means the standard error of the estimated proportion is 0.005, or 0.5 percentage points.</p><h3>4.3 Checksums and Error Detection</h3><p>Suppose we modify N addresses or mnemonic phrases and check whether the validation process detects the errors.</p><p>Let:</p><ul><li>N = total number of modified inputs tested.</li><li>K = number of modified inputs detected as invalid.</li><li>p̂ = observed error-detection rate.</li></ul><p>The formula is:</p><p>Error-detection rate = K / N</p><p>For example, if a test detects 950 errors out of 1,000 modified inputs:</p><p>Error-detection rate = 950 / 1,000 = 0.95 = 95%</p><p>This is only an illustrative example, not an experimental result from our wallet pipeline.</p><p>The actual rate depends on the types of errors introduced and the validation method used.</p><h3>5. Python experiments</h3><p>Run this code to measure the avalanche effect and address bit distribution. It uses Keccak-256, not Python’s standardized sha3_256, and generates sample private keys using the eth-account package.</p><pre><br><br>import os<br>from Crypto.Hash import keccak<br>from eth_account import Account<br><br>def keccak256(data):<br>    h = keccak.new(digest_bits=256)<br>    h.update(data)<br>    return h.digest()<br><br># Experiment 1: Avalanche effect<br>trials = 1000<br>distances = []<br><br>for _ in range(trials):<br>    original = os.urandom(32)<br>    changed = bytearray(original)<br><br>    # Flip one bit in the input<br>    changed[0] ^= 1<br><br>    hash1 = keccak256(original)<br>    hash2 = keccak256(bytes(changed))<br><br>    distance = sum(<br>        (a ^ b).bit_count()<br>        for a, b in zip(hash1, hash2)<br>    )<br>    distances.append(distance)<br><br>print(&quot;Avalanche experiment&quot;)<br>print(&quot;Trials:&quot;, trials)<br>print(&quot;Mean differing bits:&quot;, sum(distances) / trials)<br>print(&quot;Expected mean under ideal model: 128&quot;)<br><br># Experiment 2: Address-bit distribution<br>N = 10000<br>ones = [0] * 160<br><br>for _ in range(N):<br>    # Generate a fresh account using the library<br>    account = Account.create()<br>    address = bytes.fromhex(account.address[2:])<br><br>    for bit_index in range(160):<br>        byte_index = bit_index // 8<br>        bit_position = 7 - (bit_index % 8)<br>        ones[bit_index] += (<br>            address[byte_index] &gt;&gt; bit_position<br>        ) &amp; 1<br><br>proportions = [count / N for count in ones]<br><br>print(&quot;\nAddress-bit experiment&quot;)<br>print(&quot;Addresses sampled:&quot;, N)<br>print(&quot;Mean bit proportion:&quot;, sum(proportions) / 160)<br>print(&quot;Minimum bit proportion:&quot;, min(proportions))<br>print(&quot;Maximum bit proportion:&quot;, max(proportions))<br>print(&quot;Expected proportion under ideal model: 0.5&quot;)</pre><pre># Install first if needed:<br># pip install pycryptodome eth-account</pre><h4>6. Why Does the Pipeline Use Different Cryptographic Techniques?</h4><p>Each component has a specific purpose, so one algorithm cannot replace the entire pipeline.</p><ul><li><strong>BIP-39, BIP-32 and BIP-44</strong> support mnemonic creation, key derivation and wallet organization.</li><li><strong>secp256k1</strong> connects private keys to public keys and supports digital signatures.</li><li><strong>Keccak-256</strong> hashes the public key to help generate the Ethereum address.</li><li><strong>EIP-55</strong> adds a checksum through mixed capitalization, helping users detect some typing errors.</li></ul><p>Combining these techniques creates a structured process for key management, cryptographic operations and address verification.</p><h4>7. Conclusion</h4><p>The Ethereum wallet pipeline combines randomness, deterministic key derivation, elliptic-curve cryptography, hashing and checksum encoding. Statistical experiments can examine properties such as hash avalanche behaviour, address-bit frequencies and checksum error detection.</p><p>However, statistical patterns alone cannot prove that a cryptographic system is secure. Security also depends on the quality of randomness, correct implementation and the mathematical properties of the underlying algorithms. Understanding the role of each component helps explain how a wallet address is generated and why different cryptographic techniques are required.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70d6b7f54e3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Homework 1: Elliptic Curve Cryptography and Statistical Analysis of Public-Key Generation]]></title>
            <link>https://medium.com/@ramumadireddy1072/homework-1-elliptic-curve-cryptography-and-statistical-analysis-of-public-key-generation-e8551e63160e?source=rss-f08e3b6f3210------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8551e63160e</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[cyrptography]]></category>
            <dc:creator><![CDATA[RamuMadireddy]]></dc:creator>
            <pubDate>Thu, 15 Oct 2026 05:00:01 GMT</pubDate>
            <atom:updated>2026-10-15T05:00:01.970Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Introduction</h3><p>Public-key cryptography allows a person to create a public key that can be shared with others while keeping the corresponding private key secret. Elliptic Curve Cryptography (ECC) is a widely used approach to public-key cryptography because it provides strong security with relatively small keys.</p><p>The central operation studied in this homework is</p><p><strong>Q = kG</strong></p><p>where k is the private-key value, G is a publicly known base point on an elliptic curve, and Q is the resulting public point. The expression kG means adding the point G to itself k times using the elliptic-curve group operation.</p><p>This project uses the small curve</p><p><strong>y² = x³+7 (mod 17)</strong></p><p>to make the calculations easy to inspect. A browser-based JavaScript program can calculate multiples of a base point, display public-key coordinates, and collect results for statistical analysis.</p><p>The goal is not to build a secure cryptographic system. It is to understand the mathematics behind public-key generation and examine what coordinate distributions can and cannot tell us about cryptographic behavior.</p><h3>2. Mathematical background</h3><h3>2.1 The elliptic curve</h3><p>An elliptic curve over a finite field can be written in the form</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/190/1*atPFZ-EwuwvlZ7CM9EAFsg.png" /></figure><p>where p is a prime number and all coordinate calculations are performed modulo p.</p><p>For this assignment, a=0, b=7, and p=17. Therefore,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/165/1*Ux6nGyn6i8Cmz1dA3Arh2Q.png" /></figure><p>The coordinates are integers from 0 to 16. Arithmetic results are reduced modulo 17, so values remain inside the finite field.</p><p>For example, 20 mod 17 = 3. This modular arithmetic is what makes the set of possible points finite.</p><p>A point belongs to the curve only when its coordinates satisfy the equation. The curve also includes a special identity element called the point at infinity, denoted by O.</p><h3>2.2 Point addition and doubling</h3><p>Two points on an elliptic curve can be combined to produce another point on the same curve. This operation is called point addition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*zqyQ7yDfOzRAmA1ALHku8A.png" /></figure><p>Here, the inverse is a modular multiplicative inverse, not an ordinary decimal division.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/66/1*uIX50mIf2U57_pcyLz7jNQ.png" /></figure><p>When the same point is added to itself, the operation is called point doubling. For this curve, the slope becomes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/1*SQLS4wSh3LRxippZx3ykvA.png" /></figure><p>provided the denominator has an inverse and the point is not a special case. If two points have the same x-coordinate and opposite y-coordinates modulo 17, their sum is O.</p><h3>2.3 Scalar multiplication</h3><p>Scalar multiplication repeatedly applies point addition:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*ZsZNOiZ1yFu5CkZAGFMsbQ.png" /></figure><p>Instead of adding G one time at a time, an implementation can use double and add. This method reads the binary representation of k, repeatedly doubles the current point, and adds selected multiples according to the bits of the scalar.</p><p>For example, 6 in binary is 110_2, so</p><p>6G=4G+2G</p><p>where each multiple is obtained through point doubling and addition. The method reduces the number of group operations needed for larger scalars.</p><p>In real ECC, scalar multiplication is efficient, while recovering the private scalar from a public point is intended to be computationally infeasible for appropriately selected curves and key sizes.</p><h3><strong>3. Choosing a base point</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*tnmppWKEMe-npDjJhwhmOg.png" /></figure><p>Both sides are equal modulo 17, so G is a valid point.</p><p>Repeated point addition gives the following sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*KcVqLUGNui3ADnWMdDkVbA.png" /></figure><p>This table reveals that G has order 9: adding G nine times produces the identity point. The nonzero private-key examples in this subgroup are therefore k = 1,……., 8.</p><p>For instance, when k=6,</p><p>Q = 6G = (5,8)</p><p>The coordinates of Q are the toy public key. The private scalar k is the input used to calculate it.</p><h3>4. Implementation in JavaScript</h3><p>The following program implements modular arithmetic, point addition, point doubling, and scalar multiplication.</p><pre><br>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>&lt;meta charset=&quot;UTF-8&quot;&gt;<br>&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;<br>&lt;title&gt;Toy Elliptic Curve Public-Key Generator&lt;/title&gt;<br>&lt;style&gt;<br>body {<br>  max-width: 800px;<br>  margin: 35px auto;<br>  padding: 0 16px;<br>  font: 16px/1.6 system-ui, sans-serif;<br>  color: #202a35;<br>}<br>section {<br>  border: 1px solid #d7dee5;<br>  border-radius: 12px;<br>  padding: 18px;<br>  margin: 20px 0;<br>}<br>input, button {<br>  font: inherit;<br>  padding: 9px;<br>  margin: 5px 0;<br>}<br>button {<br>  cursor: pointer;<br>}<br>table {<br>  border-collapse: collapse;<br>  width: 100%;<br>}<br>th, td {<br>  text-align: left;<br>  border-bottom: 1px solid #ddd;<br>  padding: 8px;<br>}<br>.note {<br>  background: #eef4ff;<br>  padding: 12px;<br>  border-left: 4px solid #2457a7;<br>}<br>&lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>&lt;h1&gt;Toy Elliptic Curve Public-Key Generator&lt;/h1&gt;<br>&lt;p&gt;Curve: y² = x³ + 7 (mod 17)&lt;/p&gt;<br>&lt;p&gt;Base point: G = (1, 5)&lt;/p&gt;<br><br>&lt;p class=&quot;note&quot;&gt;<br>Educational demonstration only. This tiny curve is not secure<br>and must not be used for real cryptographic keys.<br>&lt;/p&gt;<br><br>&lt;section&gt;<br>  &lt;label for=&quot;key&quot;&gt;Private scalar k (1–8): &lt;/label&gt;<br>  &lt;input id=&quot;key&quot; type=&quot;number&quot; min=&quot;1&quot; max=&quot;8&quot;<br>         value=&quot;6&quot;&gt;<br>  &lt;button id=&quot;calculate&quot;&gt;Calculate&lt;/button&gt;<br>  &lt;p id=&quot;result&quot; aria-live=&quot;polite&quot;&gt;&lt;/p&gt;<br>  &lt;table&gt;<br>    &lt;thead&gt;<br>      &lt;tr&gt;&lt;th&gt;Multiple&lt;/th&gt;&lt;th&gt;Coordinates&lt;/th&gt;&lt;/tr&gt;<br>    &lt;/thead&gt;<br>    &lt;tbody id=&quot;steps&quot;&gt;&lt;/tbody&gt;<br>  &lt;/table&gt;<br>&lt;/section&gt;<br><br>&lt;section&gt;<br>  &lt;h2&gt;All valid toy private keys&lt;/h2&gt;<br>  &lt;table&gt;<br>    &lt;thead&gt;<br>      &lt;tr&gt;&lt;th&gt;k&lt;/th&gt;&lt;th&gt;x&lt;/th&gt;&lt;th&gt;y&lt;/th&gt;&lt;/tr&gt;<br>    &lt;/thead&gt;<br>    &lt;tbody id=&quot;allKeys&quot;&gt;&lt;/tbody&gt;<br>  &lt;/table&gt;<br>  &lt;p id=&quot;summary&quot;&gt;&lt;/p&gt;<br>&lt;/section&gt;<br><br>&lt;script&gt;<br>&quot;use strict&quot;;<br><br>const p = 17;<br>const G = { x: 1, y: 5 };<br>const O = null; // Point at infinity<br><br>function mod(n) {<br>  return ((n % p) + p) % p;<br>}<br><br>function inverse(n) {<br>  n = mod(n);<br>  if (n === 0) {<br>    throw new Error(&quot;Zero has no modular inverse.&quot;);<br>  }<br>  for (let i = 1; i &lt; p; i++) {<br>    if (mod(n * i) === 1) return i;<br>  }<br>  throw new Error(&quot;Inverse not found.&quot;);<br>}<br><br>function addPoints(A, B) {<br>  if (A === O) return B;<br>  if (B === O) return A;<br><br>  // A point and its inverse sum to O.<br>  if (A.x === B.x &amp;&amp; mod(A.y + B.y) === 0) {<br>    return O;<br>  }<br><br>  let slope;<br><br>  if (A.x === B.x &amp;&amp; A.y === B.y) {<br>    // Point doubling<br>    slope = mod(3 * A.x * A.x * inverse(2 * A.y));<br>  } else {<br>    // Addition of distinct points<br>    slope = mod((B.y - A.y) * inverse(B.x - A.x));<br>  }<br><br>  const x = mod(slope * slope - A.x - B.x);<br>  const y = mod(slope * (A.x - x) - A.y);<br><br>  return { x, y };<br>}<br><br>function multiply(k, point = G) {<br>  let result = O;<br>  let addend = point;<br><br>  // Double-and-add algorithm<br>  while (k &gt; 0) {<br>    if (k % 2 === 1) {<br>      result = addPoints(result, addend);<br>    }<br>    addend = addPoints(addend, addend);<br>    k = Math.floor(k / 2);<br>  }<br><br>  return result;<br>}<br><br>function formatPoint(P) {<br>  return P === O ? &quot;O&quot; : `(${P.x}, ${P.y})`;<br>}<br><br>function calculate() {<br>  const k = Number(document.getElementById(&quot;key&quot;).value);<br>  const result = document.getElementById(&quot;result&quot;);<br>  const steps = document.getElementById(&quot;steps&quot;);<br>  steps.replaceChildren();<br><br>  if (!Number.isInteger(k) || k &lt; 1 || k &gt; 8) {<br>    result.textContent = &quot;Enter an integer from 1 to 8.&quot;;<br>    return;<br>  }<br><br>  let point = O;<br><br>  for (let i = 1; i &lt;= k; i++) {<br>    point = addPoints(point, G);<br>    const row = document.createElement(&quot;tr&quot;);<br><br>    for (const value of [i + &quot;G&quot;, formatPoint(point)]) {<br>      const cell = document.createElement(&quot;td&quot;);<br>      cell.textContent = value;<br>      row.appendChild(cell);<br>    }<br>    steps.appendChild(row);<br>  }<br><br>  result.textContent =<br>    `Public key: Q = ${k}G = ${formatPoint(multiply(k))}`;<br>}<br><br>function showAllKeys() {<br>  const tbody = document.getElementById(&quot;allKeys&quot;);<br>  const xs = [];<br>  const ys = [];<br><br>  for (let k = 1; k &lt;= 8; k++) {<br>    const Q = multiply(k);<br>    xs.push(Q.x);<br>    ys.push(Q.y);<br><br>    const row = document.createElement(&quot;tr&quot;);<br>    for (const value of [k, Q.x, Q.y]) {<br>      const cell = document.createElement(&quot;td&quot;);<br>      cell.textContent = value;<br>      row.appendChild(cell);<br>    }<br>    tbody.appendChild(row);<br>  }<br><br>  const counts = values =&gt;<br>    [...new Set(values)].sort((a, b) =&gt; a - b)<br>      .map(v =&gt; `${v}: ${values.filter(x =&gt; x === v).length}`)<br>      .join(&quot;; &quot;);<br><br>  document.getElementById(&quot;summary&quot;).textContent =<br>    `x-coordinate frequencies — ${counts(xs)}. ` +<br>    `y-coordinate frequencies — ${counts(ys)}.`;<br>}<br><br>document.getElementById(&quot;calculate&quot;)<br>  .addEventListener(&quot;click&quot;, calculate);<br><br>calculate();<br>showAllKeys();<br>&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><h3>4.1 How the program works</h3><p>The program has three main mathematical functions.</p><ul><li>inverse() finds the multiplicative inverse modulo 17.</li><li>addPoints() implements point addition and doubling, including the point at infinity.</li><li>multiply() uses double-and-add to calculate kG.</li></ul><p>The interface accepts a scalar from 1 to 8, displays the successive multiples, and shows the final public point. It also lists all eight points in the subgroup so their coordinates can be compared.</p><p>The implementation is intentionally small enough to inspect. A production implementation would require a standard curve, secure private-key generation, robust validation, and constant-time cryptographic operations. This teaching program does not provide those protections.</p><h3>5. Statistical analysis of the public keys</h3><p>The second part of the homework investigates whether the generated public points show a recognizable distribution or a relationship between the private scalar and the output coordinates.</p><p>For this experiment, all eight valid nonzero scalars are tested. This makes the dataset complete for the chosen subgroup, although it is far too small to support conclusions about real cryptographic systems.</p><h3>5.1 Coordinate distribution</h3><p>The generated dataset is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*RkOw678BYPcXkL-WEbQVdw.png" /></figure><p>The x-coordinate frequencies are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*NCbHHhp8ILqy-5jXjzqUUQ.png" /></figure><p>Each of the four x-coordinates occurs twice. In contrast, all eight y-coordinates are distinct in this sample.</p><p>This pattern results from the structure of the selected elliptic-curve subgroup. In particular, the points P and -P share the same x-coordinate, while their y-coordinates are negatives of one another modulo 17.</p><p>These results demonstrate why coordinate distributions should be interpreted in the context of the underlying mathematics. The repeated x-values are not evidence of a defect in the implementation.</p><h3>5.2 Correlation between the private scalar and coordinates</h3><p>Pearson’s correlation coefficient measures the strength and direction of a linear relationship between two numerical variables. Its value ranges from -1 to +1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*9CNS_Q3x5cOorOKZcYbcdA.png" /></figure><p>The zero x-correlation follows from the symmetry of the x-coordinate sequence: x_k=x_9-k. Values equally far from the center of the sequence therefore balance around the mean scalar.</p><p>The y-coordinate has a small positive sample correlation. This does not mean that the private scalar can be predicted reliably from the y-coordinate, nor does it demonstrate a weakness in ECC. Correlation describes a particular statistical relationship; it does not measure the computational difficulty of reversing scalar multiplication.</p><p>With only eight observations, these coefficients are descriptive rather than strong statistical evidence.</p><h3>5.3 Examining avalanche like behavior</h3><p>The avalanche effect is commonly associated with cryptographic hash functions. Ideally, changing one input bit changes approximately half of the output bits, without a predictable relationship between the input difference and the output difference.</p><p>Scalar multiplication is different. Its purpose is to map a scalar to a point through a structured mathematical operation, not to act as a hash function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*UkvAJmCkb2DKtLR5zE3h1Q.png" /></figure><p>If each coordinate is represented using five bits, the coordinates are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*vVeGw92Kz6nosNzhp-crnQ.png" /></figure><p>In this example, seven out of the ten coordinate bits differ. However, one pair of inputs is not enough to establish an avalanche property. Other input pairs can produce different numbers of changed bits, and the result also depends on the representation used.</p><p>The important observation is that scalar multiplication has no requirement to produce the same bit-change behavior as a cryptographic hash.</p><h3>9. Conclusion</h3><p>This work demonstrates how elliptic curve scalar multiplication transforms a private scalar into a public point. By implementing point addition, point doubling, and double and add in JavaScript, the mathematical process becomes observable and easier to understand.</p><p>The statistical experiment shows that the resulting coordinates can exhibit patterns, including repeated x-values and nonzero or zero sample correlations. These patterns are influenced by the selected curve, base point, subgroup, and limited sample size.</p><p>The main conclusion is that public-key generation and cryptographic hashing have different mathematical purposes. ECC relies on elliptic curve group operations and the difficulty of reversing scalar multiplication. Hash functions are designed to produce fixed length digests with properties such as collision resistance and avalanche like behavior.</p><p>The small curve used here is therefore useful as a learning tool, but it is not a secure cryptographic system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8551e63160e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>