Z-test : Formula, Types, Examples
Last Updated :
24 Jul, 2025
A Z-test is a type of hypothesis test that compares the sample’s average to the population’s average and calculates the Z-score and tells us how much the sample average is different from the population average by looking at how much the data normally varies. It is particularly useful when the sample size is large >30. This Z-Score is also known as Z-Statistics formula is:
\text{Z-Score} = \frac{\bar{x}-\mu}{\sigma}
where,
- \bar{x}
: mean of the sample.
- \mu
: mean of the population.
- \sigma
: Standard deviation of the population.
Let's understand with the help of example The average family annual income in India is 200k with a standard deviation of 5k and the average family annual income in Delhi is 300k. Then Z-Score for Delhi will be.
\begin{aligned}\text{Z-Score}&=\frac{\bar{x}-\mu}{\sigma}\\&=\frac{300-200}{5}\\&=20\end{aligned}
This indicates that the average family's annual income in Delhi is 20 standard deviations above the mean of the population (India).
For a z-test to provide reliable results these assumptions must be met:
- Normal Distribution: The population from which the sample is drawn should be approximately normally distributed.
- Equal Variance: The samples being compared should have the same variance.
- Independence: All data points should be independent of one another.
1. First we identify the null and alternate hypotheses.
2. Then we determine the level of significance (\alpha).
3. Next we find the critical value of Z in the z-test.
4. Then we calculate the z-test statistics using the formula :
Z=\frac{(\overline{x}- \mu)}{\left ( \sigma /\sqrt{n} \right )}
Where:
- \bar{x}
: mean of the sample.
- \mu
: mean of the population.
- \sigma
: Standard deviation of the population.
- n : sample size.
5. Now we compare with the hypothesis and decide whether to reject or not reject the null hypothesis.
Type of Z-test
There are mainly two types of Z-tests. Let's understand them one by one:
1. One Sample Z test
A one-sample Z-test is used to determine if the mean of a single sample is significantly different from a known population mean. When to Use:
- The population standard deviation is known.
- The sample size is large (usually n>30).
- The data is approximately normally distributed.
Suppose a company claims that their new smartphone has an average battery life of 12 hours. A consumer group tests 100 phones and finds an average battery life of 11.8 hours with a known population standard deviation of 0.5 hours.
Step 1: Hypotheses:
- H_0 : \mu = 12:
- H_1 : \mu\neq 12
Step2: Calculate the Z-Score:
We can calculate Z-score using the formula:
z = \frac{x - \mu}{\frac{\sigma}{\sqrt{n}}}
Where: \bar{x}= 11.8 , \mu= 12, \sigma= 0.5 and n= 100
After putting the value we get:
z = \frac{11.8- 12}{\frac{0.5}{\sqrt{100}}} = -4
Step3: Decision
Since \left| Z \right| = 4 > 1.96 (critical value for\alpha = 0.05) we reject H_0 indicate significant evidence against the company's claim.
Now let's implement this in Python using the Statsmodels and Numpy Library:
Python
import numpy as np
from statsmodels.stats.weightstats import ztest
data = [11.8] * 100
population_mean = 12
population_std_dev = 0.5
z_statistic, p_value = ztest(data, value=population_mean)
print(f"Z-Statistic: {z_statistic:.4f}")
print(f"P-Value: {p_value:.4f}")
alpha = 0.05
if p_value < alpha:
print("Reject the null hypothesis: The average battery life is different from 12 hours.")
else:
print("Fail to reject the null hypothesis: The average battery life is not significantly different from 12 hours.")
Output:
Z-Statistic: -560128131373970.2500
P-Value: 0.0000
Reject the null hypothesis: The average battery life is different from 12 hour
2. Two-sampled z-test
In this test we have provided 2 normally distributed and independent populations and we have drawn samples at random from both populations. Here we consider u_1 and u_2 to be the population mean and X_1 and X_2 to be the observed sample mean. Here our null hypothesis could be like this:
- H_{0} : \mu_{1} -\mu_{2} = 0 and alternative hypothesis
- H_{1} : \mu_{1} - \mu_{2} \ne 0
and the formula for calculating the z-test score:
Z = \frac{\left ( \overline{X_{1}} - \overline{X_{2}} \right ) - \left ( \mu_{1} - \mu_{2} \right )}{\sqrt{\frac{\sigma_{1}^2}{n_{1}} + \frac{\sigma_{2}^2}{n_{2}}}}
where \sigma_1 and \sigma_2 are the standard deviation and n_1 and n_2 are the sample size of population corresponding to u_1 and u_2 . Let's look at the example to understand:
Example: There are two groups of students preparing for a competition: Group A and Group B. Group A has studied offline classes, while Group B has studied online classes. After the examination the score of each student comes. Now we want to determine whether the online or offline classes are better.
- Group A: Sample size = 50, Sample mean = 75, Sample standard deviation = 10
- Group B: Sample size = 60, Sample mean = 80, Sample standard deviation = 12
Assuming a 5% significance level perform a two-sample z-test to determine if there is a significant difference between the online and offline classes.
Solution:
Step 1: Null & Alternate Hypothesis
- Null Hypothesis: There is no significant difference between the mean score between the online and offline classes
\mu_1 -\mu_2 = 0
- Alternate Hypothesis: There is a significant difference in the mean scores between the online and offline classes.
\mu_1 -\mu_2 \neq 0
Step 2: Significance Level
- Significance Level: 5%
\alpha = 0.05
Step 3: Z-Score
\begin{aligned}\text{Z-score} &= \frac{(x_1-x_2)-(\mu_1 -\mu_2)}{\sqrt{\frac{\sigma_1^2}{n_1}+\frac{\sigma_2^2}{n_1}}}\\ &= \frac{(75-80)-0}{\sqrt{\frac{10^2}{50}+\frac{12^2}{60}}}\\ &= \frac{-5}{\sqrt{2+2.4}}\\ &= \frac{-5}{2.0976}\\&=-2.384\end{aligned}
Step 4: Check to Critical Z-Score value in the Z-Table for alpha/2 = 0.025
Step 5: Compare with the absolute Z-Score value
- absolute(Z-Score) > Critical Z-Score
- Sow we reject the null hypothesis and there is a significant difference between the online and offline classes.
Now we will implement the two sampled z-test using numpy and scipy.
Python
import numpy as np
import scipy.stats as stats
n1 = 50
x1 = 75
s1 = 10
n2 = 60
x2 = 80
s2 = 12
D = 0
alpha = 0.05
z_score = ((x1 - x2) - D) / np.sqrt((s1**2 / n1) + (s2**2 / n2))
print('Z-Score:', np.abs(z_score))
z_critical = stats.norm.ppf(1 - alpha/2)
print('Critical Z-Score:',z_critical)
if np.abs(z_score) > z_critical:
print("Reject the null hypothesis.")
else:
print("Fail to reject the null hypothesis.")
Output:
Z-Score: 2.3836564731139807
Critical Z-Score: 1.959963984540054
Reject the null hypothesis.
So, There is a significant difference between the online and offline classes.
The Z-Table
Z-TableSolved examples
Problem 1: A company claims that the average battery life of their new smartphone is 12 hours. A consumer group tests 100 phones and finds the average battery life to be 11.8 hours with a population standard deviation of 0.5 hours. At a 5% significance level, is there evidence to refute the company's claim?
Solution:
Step 1: State the hypotheses
H_0: \mu = 12 \quad (\text{null hypothesis}) \\H_1: \mu \neq 12 \quad (\text{alternative hypothesis})
Step 2: Calculate the Z-score
Z = \frac{\bar{x} - \mu}{\frac{\sigma}{\sqrt{n}}} \\= \frac{11.8 - 12}{\frac{0.5}{\sqrt{100}}} \\= \frac{-0.2}{0.05} \\= -4
Step 3: Find the critical value (two-tailed test at 5% significance)
Z_{0.025} = \pm 1.96
Step 4: Compare Z-score with critical value
|-4| > 1.96, so we reject the null hypothesis.
Conclusion: There is sufficient evidence to refute the company's claim about battery life.
Problem 2: A researcher wants to compare the effectiveness of two different medications for reducing blood pressure. Medication A is tested on 50 patients, resulting in a mean reduction of 15 mmHg with a standard deviation of 3 mmHg. Medication B is tested on 60 patients, resulting in a mean reduction of 13 mmHg with a standard deviation of 4 mmHg. At a 1% significance level, is there a significant difference between the two medications?
Solution:
Step 1: State the hypotheses
H_0: \mu_1 - \mu_2 = 0 \quad (\text{null hypothesis}) \\H_1: \mu_1 - \mu_2 \neq 0 \quad (\text{alternative hypothesis})
Step 2: Calculate the Z-score
Z = \frac{\bar{x}_1 - \bar{x}_2}{\sqrt{\frac{\sigma_1^2}{n_1} + \frac{\sigma_2^2}{n_2}}} \\= \frac{15 - 13}{\sqrt{\frac{3^2}{50} + \frac{4^2}{60}}} \\= \frac{2}{\sqrt{0.18 + 0.2667}} \\= \frac{2}{0.6455} \\= 3.10
Step 3: Find the critical value (two-tailed test at 1% significance)
Z_{0.005} = \pm 2.576
Step 4: Compare Z-score with critical value
3.10 > 2.576, so we reject the null hypothesis.
Z-test : Formula, Types, Examples
Z-test : Formula, Types, Examples
Z-Test
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem