Otto vs Diesel Cycle in Python: Efficiency and P-V Diagram

The Otto and Diesel cycles are in every thermodynamics syllabus, and most students meet them as a set of formulas to memorise. Solving them in Python makes the cycles visible: you get every state point, the net work, the efficiency and a proper P-V diagram from about 90 lines of code. In this tutorial we model the ideal Otto vs Diesel cycle in Python, compare their efficiency and plot both loops on one graph.

Quick answer: Ideal Otto efficiency is η = 1 − 1/rγ−1 and ideal Diesel efficiency is η = 1 − (1/rγ−1)·(rcγ − 1)/[γ(rc − 1)], where r is the compression ratio and rc the cut-off ratio. In Python, compute the four states with the isentropic relations, get efficiency from the net work, and draw the P-V loop with P·vγ = constant. With 1800 kJ/kg of heat added, Otto at r = 8 gives 56.4 % and Diesel at r = 18 gives 59.4 %.

The Problem

  • Air-standard cycles with cold-air properties: cp = 1.005, cv = 0.718 kJ/kg·K, R = 0.287 kJ/kg·K, γ ≈ 1.4
  • Intake state: P1 = 100 kPa, T1 = 300 K
  • Heat added: qin = 1800 kJ/kg for both cycles
  • Petrol (Otto) engine: compression ratio r = 8
  • Diesel engine: compression ratio r = 18

We want the temperature and pressure at all four states, the net work, the thermal efficiency, the mean effective pressure (MEP) and the P-V diagram of both cycles.

Step 1: The Theory

Both ideal cycles have four processes. 1→2 is isentropic compression, so T2 = T1rγ−1 and P2 = P1rγ. 3→4 is isentropic expansion and 4→1 is heat rejection at constant volume. The only difference is 2→3, the heat addition:

  • Otto: heat is added at constant volume (spark ignition, fast combustion), so qin = cv(T3 − T2) and pressure jumps sharply.
  • Diesel: heat is added at constant pressure (fuel injected and burned as the piston moves), so qin = cp(T3 − T2) and the volume grows by the cut-off ratio rc = v3/v2.

Efficiency is the net work divided by the heat added: η = (qin − qout)/qin, with qout = cv(T4 − T1). A quick hand check for the Otto cycle: 1 − 1/80.4 = 1 − 1/2.297 = 56.5 %. The code gives 56.4 % because cp/cv = 1.3997, not exactly 1.4. MEP is the net work divided by the swept volume, v1 − v2.

Step 2: The Python Code

You need Python with NumPy and Matplotlib (pip install numpy matplotlib). Each cycle is one function that returns its state points and results. A separate function builds the smooth P-V loop, and at the end the script checks the efficiency from the energy balance against the textbook formulas.

import numpy as np
import matplotlib.pyplot as plt

# Air-standard properties (cold-air assumptions)
R = 0.287      # gas constant, kJ/kg.K
cp = 1.005     # kJ/kg.K
cv = 0.718     # kJ/kg.K
k = cp / cv    # ratio of specific heats (about 1.4)

# Intake state (state 1) and heat added per kg of air
P1, T1 = 100.0, 300.0   # kPa, K
q_in = 1800.0           # kJ/kg


def otto(r):
    """Ideal Otto cycle: isentropic compression, heat at constant volume."""
    v1 = R * T1 / P1
    v2 = v1 / r
    T2 = T1 * r**(k - 1)
    P2 = P1 * r**k
    T3 = T2 + q_in / cv              # constant-volume heat addition
    P3 = P2 * T3 / T2
    T4 = T3 / r**(k - 1)             # isentropic expansion
    P4 = P3 / r**k
    q_out = cv * (T4 - T1)
    w_net = q_in - q_out
    return dict(name=f"Otto (r = {r})", v=[v1, v2, v2, v1], P=[P1, P2, P3, P4],
                T=[T1, T2, T3, T4], w_net=w_net, eta=w_net / q_in,
                mep=w_net / (v1 - v2))


def diesel(r):
    """Ideal Diesel cycle: isentropic compression, heat at constant pressure."""
    v1 = R * T1 / P1
    v2 = v1 / r
    T2 = T1 * r**(k - 1)
    P2 = P1 * r**k
    T3 = T2 + q_in / cp              # constant-pressure heat addition
    rc = T3 / T2                     # cut-off ratio v3/v2
    v3 = rc * v2
    P3 = P2
    T4 = T3 * (v3 / v1)**(k - 1)     # isentropic expansion back to v1
    P4 = P3 * (v3 / v1)**k
    q_out = cv * (T4 - T1)
    w_net = q_in - q_out
    return dict(name=f"Diesel (r = {r})", v=[v1, v2, v3, v1], P=[P1, P2, P3, P4],
                T=[T1, T2, T3, T4], w_net=w_net, eta=w_net / q_in,
                mep=w_net / (v1 - v2), rc=rc)


def pv_curve(c, n=60):
    """Points for a smooth P-v loop (isentropic lines follow P v^k = const)."""
    v1, v2, v3, v4 = c["v"]
    P1_, P2_, P3_, P4_ = c["P"]
    v12 = np.linspace(v1, v2, n); p12 = P1_ * (v1 / v12)**k   # compression
    v23 = np.array([v2, v3]);     p23 = np.array([P2_, P3_])   # heat addition
    v34 = np.linspace(v3, v4, n); p34 = P3_ * (v3 / v34)**k   # expansion
    v41 = np.array([v4, v1]);     p41 = np.array([P4_, P1_])   # heat rejection
    return np.concatenate([v12, v23, v34, v41]), np.concatenate([p12, p23, p34, p41])


cycles = [otto(8), diesel(18), otto(18)]

print(f"k = {k:.3f}, heat added = {q_in:.0f} kJ/kg\n")
for c in cycles:
    print(c["name"])
    for i, (T, P) in enumerate(zip(c["T"], c["P"]), start=1):
        print(f"  State {i}: T = {T:7.1f} K   P = {P:8.1f} kPa")
    if "rc" in c:
        print(f"  Cut-off ratio      = {c['rc']:.2f}")
    print(f"  Net work           = {c['w_net']:.1f} kJ/kg")
    print(f"  Thermal efficiency = {c['eta']*100:.1f} %")
    print(f"  MEP                = {c['mep']:.0f} kPa\n")

# Cross-check efficiency with the textbook formulas
r = 8
print(f"Formula check Otto r=8:    {(1 - 1/r**(k-1))*100:.1f} %")
r, rc = 18, cycles[1]["rc"]
eta_d = 1 - (1 / r**(k - 1)) * (rc**k - 1) / (k * (rc - 1))
print(f"Formula check Diesel r=18: {eta_d*100:.1f} %")

plt.figure(figsize=(8, 5))
for c in cycles[:2]:
    v, p = pv_curve(c)
    plt.plot(v, p / 1000, label=f"{c['name']}, efficiency {c['eta']*100:.1f} %")
plt.xlabel("Specific volume, v (m³/kg)")
plt.ylabel("Pressure, P (MPa)")
plt.title("P-V diagram: ideal Otto vs Diesel cycle (1800 kJ/kg heat added)")
plt.grid(True, alpha=0.3)
plt.legend()
plt.tight_layout()
plt.savefig("otto_vs_diesel_pv.png", dpi=150)
plt.show()

Step 3: The Results

Running the script prints:

k = 1.400, heat added = 1800 kJ/kg

Otto (r = 8)
  State 1: T =   300.0 K   P =    100.0 kPa
  State 2: T =   688.8 K   P =   1836.9 kPa
  State 3: T =  3195.8 K   P =   8522.1 kPa
  State 4: T =  1391.9 K   P =    464.0 kPa
  Net work           = 1016.1 kJ/kg
  Thermal efficiency = 56.4 %
  MEP                = 1349 kPa

Diesel (r = 18)
  State 1: T =   300.0 K   P =    100.0 kPa
  State 2: T =   952.5 K   P =   5715.2 kPa
  State 3: T =  2743.6 K   P =   5715.2 kPa
  State 4: T =  1318.9 K   P =    439.6 kPa
  Cut-off ratio      = 2.88
  Net work           = 1068.4 kJ/kg
  Thermal efficiency = 59.4 %
  MEP                = 1314 kPa

Otto (r = 18)
  State 1: T =   300.0 K   P =    100.0 kPa
  State 2: T =   952.5 K   P =   5715.2 kPa
  State 3: T =  3459.5 K   P =  20757.0 kPa
  State 4: T =  1089.6 K   P =    363.2 kPa
  Net work           = 1233.1 kJ/kg
  Thermal efficiency = 68.5 %
  MEP                = 1516 kPa

Formula check Otto r=8:    56.4 %
Formula check Diesel r=18: 59.4 %

The efficiency calculated from the energy balance matches the textbook formula for both cycles. This is the first check you should always make. The P-V diagram shows both loops:

P-V diagram of ideal Otto and Diesel cycles plotted in Python with efficiency comparison
Ideal Otto (r = 8) and Diesel (r = 18) cycles with 1800 kJ/kg heat added, plotted with Python.

What the Graph Tells You

  • The Otto loop has a vertical line at 2→3 (constant-volume heat addition) and the highest peak pressure, 8.5 MPa.
  • The Diesel loop has a flat top at 2→3 (constant-pressure heat addition). Its peak pressure is lower (5.7 MPa) even though it is compressed 18 times instead of 8.
  • The area inside each loop is the net work. Diesel gives 1068 kJ/kg against 1016 kJ/kg for Otto from the same heat input, so it is more efficient: 59.4 % vs 56.4 %.
  • At the same compression ratio, Otto wins. The script also runs Otto at r = 18 and gets 68.5 %. Diesel engines are more efficient in practice only because they can use a high compression ratio without knock.
  • MEP is similar (1349 vs 1314 kPa), so for the same swept volume both engines give a similar work output per cycle.

Common Mistakes

  • Using cv for Diesel heat addition – the Diesel cycle adds heat at constant pressure, so it must be cp(T3 − T2).
  • Expanding with r instead of v4/v3 in the Diesel cycle – expansion starts at v3 = rcv2, so the expansion ratio is r/rc, not r.
  • Mixing kPa and Pa – with R in kJ/kg·K, keep pressure in kPa so that v = RT/P comes out in m³/kg.
  • Comparing at different heat inputs – keep qin or peak temperature the same, otherwise the comparison has no meaning.

Try It Yourself: Extend the Code

  1. Add the dual (mixed) cycle, with part of the heat at constant volume and part at constant pressure.
  2. Plot efficiency against compression ratio for r = 4 to 24 for Otto and Diesel on one graph.
  3. Draw the T-s diagram of both cycles using Δs = cvln(T2/T1) + R ln(v2/v1).
  4. Use temperature-dependent specific heats and see how much the efficiency drops.
  5. Compare the ideal results with real engine test data (brake power and fuel consumption) to estimate the losses.

Steps 2 to 5 together make a good Python-based thermal engineering project. If you like engine topics, also see our V6 engine design with ceramic-coated piston project and our IC engine projects, and more ideas in Python projects for final year students.

More Python for Engineers tutorials: beam deflection in Python, heat exchanger design in Python (LMTD method) and how to plot CFD and FEA results with Python Matplotlib.

Also try: spur gear design in Python – bending and contact stress and vibration analysis in Python with FFT.

Learn Python for Mechanical Engineering

This tutorial is part of how we teach Python to mechanical and automobile students – through engineering problems you already know, not abstract examples. In our Python for mechanical engineers classes you learn NumPy, Matplotlib and data handling step by step, in live screen-share sessions or recorded videos, and write the code yourself.

Frequently Asked Questions

Why is the Diesel cycle more efficient than the Otto cycle in real engines?

For the same compression ratio the Otto cycle is actually more efficient. Diesel engines win in practice because they can run at a much higher compression ratio (about 14 to 22) without knock, while petrol engines are limited to about 8 to 12. In our example, Diesel at r = 18 gives 59.4 % against 56.4 % for Otto at r = 8.

What is the formula for Otto cycle efficiency?

The ideal Otto cycle efficiency is 1 − 1/r^(γ−1), where r is the compression ratio and γ is the ratio of specific heats (about 1.4 for air). It depends only on the compression ratio.

What is the cut-off ratio in a Diesel cycle?

The cut-off ratio is the volume at the end of heat addition divided by the volume at the end of compression (v3/v2). A larger cut-off ratio means more fuel is burned at constant pressure, which lowers the Diesel cycle efficiency.

How do you draw a P-V diagram in Python?

Calculate the four state points, then generate the compression and expansion curves with P·v^γ = constant using NumPy, join them with the constant-volume or constant-pressure heat lines, and plot pressure against specific volume with Matplotlib.

Is an engine cycle calculator a good final year project?

On its own it is a small exercise. Extended with the dual cycle, real-engine losses, parametric plots of efficiency against compression ratio and a comparison with engine test data, it becomes a solid Python-based thermal engineering project.

Start Learning

Tell us your branch and what you want to build. Message us on WhatsApp or use the enquiry form on our home page.

Interested in this project? Get the details, files and guidance from our team.

Enquire on WhatsApp

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top