Temperature and Top-p Explained: Why the Same Prompt Gives Different Answers

Temperature and Top-p Explained: Why the Same Prompt Gives Different Answers featured illustration

📎 This article includes 1 downloadable practice file ↓

⏱ 2 min readUpdated 28 September 2026

An LLM does not choose the next word directly. It gives every possible token a score, turns the scores into probabilities, then samples. Temperature and top-p control that last step.

In this article
  1. A worked example
  2. Top-p (nucleus sampling)
  3. Which settings to use
  4. Continue learning

A worked example

Suppose three candidate tokens have scores (logits) 2.0, 1.0 and 0.1. Divide by the temperature, then apply softmax:

Advertisement
Temperature Token A Token B Token C
0.5 (focused) 86% 12% 2%
1.0 (default) 66% 24% 10%
2.0 (wild) 50% 31% 19%

Low temperature sharpens the distribution toward the top choice; high temperature flattens it so unlikely tokens appear more often. Temperature 0 means “always take the top token” (nearly deterministic).

import numpy as np
def softmax_t(logits, t):
    z = np.array(logits) / t
    e = np.exp(z - z.max())
    return (e / e.sum()).round(2)
print(softmax_t([2.0, 1.0, 0.1], 0.5), softmax_t([2.0, 1.0, 0.1], 2.0))

Top-p (nucleus sampling)

Top-p keeps only the smallest set of tokens whose probabilities add up to p, then samples among them. With top_p = 0.9 in the default row above, A + B = 90%, so C is never chosen. It cuts off the long tail of weird tokens while still allowing variety.

Which settings to use

Task Temperature
Formulas, SQL, code, data extraction 0–0.3
Emails, summaries, explanations 0.5–0.8
Brainstorming names, stories, slogans 0.9–1.2
💡 Change temperature or top-p, not both at once — they overlap, and tuning both makes results hard to reason about.

We implement sampling ourselves in Lesson 8 of the free Build Your Own LLM course.

📎 Practice files for this article

  • 🐍
    All code from this post1 examples in one file, ready to open in your editor.
    ⬇ PY · 457 B

Free to use for learning. Files with macros (.bas) are plain text — import them with Alt+F11 → File → Import File, and always test on a copy.

✨ Ask AI about this article

Stuck on a step? Ask a question and the AI answers using this article.

Free · AI can be wrong