Skip to content
This repository was archived by the owner on Feb 27, 2026. It is now read-only.

Commit 5ce265e

Browse files
authored
Merge branch 'main' into add-first-click-test
2 parents a82a5ea + a301294 commit 5ce265e

156 files changed

Lines changed: 14504 additions & 2221 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

content/ai/concepts/search-algorithms/terms/beam-search/beam-search.md

Lines changed: 63 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,19 +2,20 @@
22
Title: 'BEAM Search'
33
Description: 'A graph searching algorithm that is a variant of breadth-first search.'
44
Subjects:
5-
- 'Data Science'
65
- 'AI'
6+
- 'Data Science'
77
Tags:
8-
- 'Search Algorithms'
98
- 'AI'
9+
- 'Algorithms'
10+
- 'Search Algorithms'
1011
CatalogContent:
1112
- 'learn-python-3'
12-
- 'paths/machine-learning-ai-engineering-foundations'
13+
- 'paths/computer-science'
1314
---
1415

1516
**BEAM Search**, a variant of [breadth-first Search](https://www.codecademy.com/resources/docs/ai/search-algorithms/breadth-first-search), is an algorithm that searches a weighted graph for an optimal path from some start node **S** to some goal node **G**. The difference between BEAM search and breadth-first search is that at every level of the search tree, only the top _β_ candidates are chosen for further exploration. Here, β is known as the _beam width_. The reasoning behind this is that a path from **S** to **G** is likely to pass through some top number of most promising nodes. This leads to an algorithm that is fast and memory-efficient because it can disregard many nodes that may appear to be too far from the goal. This, however, sometimes causes the algorithm to overlook a potential shortest path because a candidate node is greater than the beam width. This renders the algorithm as _incomplete_, meaning that finding the shortest path is not guaranteed. Since the algorithm can find a reasonably short path, trading completeness for efficiency is accepted. Much like [A\* search](https://www.codecademy.com/resources/docs/ai/search-algorithms/a-star-search) and [best-first search](https://www.codecademy.com/resources/docs/ai/search-algorithms/best-first-search), an evaluation function is used to evaluate the candidacy of nodes for further exploration.
1617

17-
## The Algorithm
18+
## How the Beam Search Algorithm Works
1819

1920
Similar to A\* search, the algorithm uses an **open list** and a **closed list** for the exploration of nodes. In this algorithm, the open list is an ordinary queue. The algorithm begins with a start node **S**, which also serves as the root node for the search tree.
2021

@@ -58,10 +59,67 @@ It is in this step that node **G** has been found:
5859
Trace the path from **S** to **G**:
5960
![Final-path](https://raw.githubusercontent.com/Codecademy/docs/main/media/BEAM-Search-final-path.png)
6061

61-
## Advantages and Disadvantages
62+
## Pseudocode for Beam Search Algorithm
63+
64+
```plaintext
65+
function BEAM_SEARCH(start_node, goal_test, beam_width, max_depth):
66+
current_level ← [start_node]
67+
depth ← 0
68+
69+
while current_level is not empty AND depth < max_depth:
70+
all_successors ← []
71+
72+
// Generate all successors from current level
73+
for each node in current_level:
74+
if goal_test(node):
75+
return SUCCESS (node)
76+
77+
successors ← get_successors(node)
78+
for each successor in successors:
79+
successor.score ← evaluation_function(successor)
80+
all_successors.append(successor)
81+
82+
if all_successors is empty:
83+
return FAILURE
84+
85+
// Sort all successors by their scores (best first)
86+
sorted_successors ← sort(all_successors, by=score, descending=True)
87+
88+
// Keep only top beam_width candidates for next level
89+
current_level ← sorted_successors[0 : beam_width]
90+
depth ← depth + 1
91+
92+
// Check final level for goal
93+
for each node in current_level:
94+
if goal_test(node):
95+
return SUCCESS (node)
96+
97+
return FAILURE
98+
```
99+
100+
## Advantages and Disadvantages of Beam Search
62101

63102
As stated before, the advantage of BEAM search is that it is efficient both in time and memory. The disadvantage can be seen from the example in that a possible shortest path from **S** to **G** was overlooked. This can be somewhat corrected by varying the beam width to include more nodes. This, however, would reduce the efficiency of the algorithm. Selecting the optimal beam width is problem-specific and usually requires further insight into the problem.
64103

65104
## Applications of BEAM Search
66105

67106
The BEAM search algorithm is commonly used in natural language processing and machine translation. An encoder is used to process the text from the source language and BEAM search selects the most probable words (the beam width) in the target language. The evaluation function in this context is the conditional probability of a word in the target language.
107+
108+
## Frequently Asked Questions
109+
110+
### 1. Is ChatGPT using beam search?
111+
112+
No, ChatGPT (and most large language models from OpenAI) doesn't use beam search during inference. It uses sampling-based decoding methods like top-k sampling, top-p (nucleus) sampling, or temperature-controlled sampling to generate text.
113+
114+
### 2. Where is beam search used?
115+
116+
Beam search is widely used in natural language processing (NLP) tasks where sequential predictions are needed:
117+
118+
- Machine translation (e.g., translating English to French)
119+
- Speech recognition
120+
- Text generation (in some models)
121+
- Optical character recognition (OCR)
122+
123+
### 3. What are the benefits of beam search?
124+
125+
Beam search is faster and more memory-efficient than exhaustive search. It explores only the most promising paths, giving better results than greedy search while still being customizable through the beam width. However, it might miss the optimal path.
Lines changed: 138 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,74 +1,182 @@
11
---
2-
Title: '.Abs()'
3-
Description: 'Computes the non-negative value of a number regardless of its sign.'
2+
Title: 'Abs()'
3+
Description: 'Returns the absolute value of a specified number.'
44
Subjects:
5-
- 'Code Foundations'
65
- 'Computer Science'
6+
- 'Web Development'
77
Tags:
8+
- 'Functions'
9+
- 'Math'
810
- 'Methods'
911
- 'Numbers'
10-
- 'Arithmetic'
11-
- 'Functions'
1212
CatalogContent:
1313
- 'learn-c-sharp'
1414
- 'paths/computer-science'
1515
---
1616

17-
The **`Math.Abs()`** class method returns the absolute value of a given number.
17+
The C# **`Math.Abs()`** method is a static method that returns the absolute value of a specified number. The absolute value of a number is its distance from zero on the number line, always expressed as a positive value or zero.
1818

19-
## Syntax
19+
## Syntax of C# `Math.Abs()`
2020

2121
```pseudo
2222
Math.Abs(number);
2323
```
2424

25-
The `Math.Abs()` method takes only one parameter, `number`, a `decimal`, `double` or `integer` type number. The method returns the absolute value of the `number` with the same type as the `number`, except if the value of `number` equals:
25+
**Parameters:**
26+
27+
- `number`: The numeric value for which to calculate the absolute value. This can be of type `decimal`, `double`, `float`, `int`, `long`, `sbyte`, `short`, or `IntPtr`.
28+
29+
**Return value:**
2630

27-
- `NaN` (not a number), then it returns `NaN`
28-
- `NegativeInfinity`, then it returns `PositiveInfinity`
29-
- `PositiveInfinity`, then it also returns `PositiveInfinity`
31+
Returns the absolute value of the specified number with the same data type as the input parameter. Special cases include:
3032

31-
## Example
33+
- If the input is `NaN` (Not a Number), returns `NaN`
34+
- If the input is negative infinity, returns positive infinity
35+
- If the input is positive infinity, returns positive infinity
3236

33-
The following example uses the `Math.Abs()` method to return the absolute value of a `decimal` and a `double` type number. Then, the `Console.WriteLine()` function prints the results to the console:
37+
## Example 1: Basic Usage of C# `Math.Abs()`
38+
39+
This example demonstrates the fundamental use of the `Math.Abs()` method with different numeric types to show how it returns the non-negative equivalent of the number:
3440

3541
```cs
3642
using System;
3743

38-
public class Example {
39-
public static void Main() {
40-
decimal num1 = -1.23M;
41-
double num2 = 6.674E-11;
44+
public class BasicAbsExample
45+
{
46+
public static void Main()
47+
{
48+
// Integer examples
49+
int negativeInt = -42;
50+
int positiveInt = 15;
51+
52+
// Decimal examples
53+
decimal negativeDecimal = -3.14m;
54+
decimal positiveDecimal = 2.71m;
55+
56+
// Calculate absolute values
57+
int absInt1 = Math.Abs(negativeInt);
58+
int absInt2 = Math.Abs(positiveInt);
59+
decimal absDecimal1 = Math.Abs(negativeDecimal);
60+
decimal absDecimal2 = Math.Abs(positiveDecimal);
61+
62+
// Display results
63+
Console.WriteLine($"Math.Abs({negativeInt}) = {absInt1}");
64+
Console.WriteLine($"Math.Abs({positiveInt}) = {absInt2}");
65+
Console.WriteLine($"Math.Abs({negativeDecimal}) = {absDecimal1}");
66+
Console.WriteLine($"Math.Abs({positiveDecimal}) = {absDecimal2}");
67+
}
68+
}
69+
```
70+
71+
The output of this code is as follows:
72+
73+
```shell
74+
Math.Abs(-42) = 42
75+
Math.Abs(15) = 15
76+
Math.Abs(-3.14) = 3.14
77+
Math.Abs(2.71) = 2.71
78+
```
79+
80+
## Example 2: Calculating Temperature Difference using `Math.Abs()`
81+
82+
This example shows how `Math.Abs()` can be used in a real-world scenario to calculate the temperature difference between two values, which is always expressed as a positive number:
4283

43-
decimal abs1 = Math.Abs(num1);
44-
double abs2 = Math.Abs(num2);
84+
```cs
85+
using System;
4586

46-
Console.WriteLine("The absolute value of " + num1 + " is: " + abs1);
47-
Console.WriteLine("The absolute value of " + num2 + " is: " + abs2);
87+
public class TemperatureDifference
88+
{
89+
public static void Main()
90+
{
91+
// Temperature readings in Celsius
92+
double morningTemp = -5.2;
93+
double afternoonTemp = 18.7;
94+
double eveningTemp = 12.3;
95+
96+
// Calculate temperature differences
97+
double morningAfternoonDiff = Math.Abs(afternoonTemp - morningTemp);
98+
double afternoonEveningDiff = Math.Abs(eveningTemp - afternoonTemp);
99+
double morningEveningDiff = Math.Abs(eveningTemp - morningTemp);
100+
101+
// Display results
102+
Console.WriteLine("Temperature Analysis:");
103+
Console.WriteLine($"Morning: {morningTemp}C");
104+
Console.WriteLine($"Afternoon: {afternoonTemp}C");
105+
Console.WriteLine($"Evening: {eveningTemp}C");
106+
Console.WriteLine();
107+
Console.WriteLine("Temperature Differences:");
108+
Console.WriteLine($"Morning to Afternoon: {morningAfternoonDiff}C");
109+
Console.WriteLine($"Afternoon to Evening: {afternoonEveningDiff}C");
110+
Console.WriteLine($"Morning to Evening: {morningEveningDiff}C");
48111
}
49112
}
50113
```
51114

52-
The example will result in the following output:
115+
The output of this code is as follows:
53116

54117
```shell
55-
The absolute value of -1.23 is: 1.23
56-
The absolute value of 6.674E-11 is: 6.674E-11
118+
Temperature Analysis:
119+
Morning: -5.2°C
120+
Afternoon: 18.7°C
121+
Evening: 12.3°C
122+
123+
Temperature Differences:
124+
Morning to Afternoon: 23.9°C
125+
Afternoon to Evening: 6.4°C
126+
Morning to Evening: 17.5°C
57127
```
58128

59-
## Codebyte Example
129+
## Codebyte Example: Financial Loss Calculator Using `Math.Abs()`
60130

61-
The following example is runnable and returns the absolute value of a `double` type number:
131+
This example demonstrates using `Math.Abs()` in financial applications to calculate the magnitude of profit or loss, regardless of whether the value is positive or negative:
62132

63133
```codebyte/csharp
64134
using System;
65135
66-
public class Example {
136+
public class FinancialLossCalculator
137+
{
138+
public static void Main()
139+
{
140+
// Investment performance data
141+
decimal[] monthlyReturns = { 150.75m, -89.50m, 245.30m, -175.25m, 95.60m };
142+
string[] months = { "January", "February", "March", "April", "May" };
143+
144+
decimal totalAbsoluteChange = 0;
145+
146+
Console.WriteLine("Monthly Investment Performance:");
147+
Console.WriteLine("Month\t\tReturn\t\tAbsolute Change");
148+
Console.WriteLine("-----------------------------------------------");
67149
68-
public static void Main() {
69-
double number = 299792458;
150+
for (int i = 0; i < monthlyReturns.Length; i++)
151+
{
152+
decimal absoluteChange = Math.Abs(monthlyReturns[i]);
153+
totalAbsoluteChange += absoluteChange;
70154
71-
Console.WriteLine("The absolute value of " + number + " is: " + Math.Abs(number));
155+
string returnType = monthlyReturns[i] >= 0 ? "Profit" : "Loss";
156+
Console.WriteLine($"{months[i]}\t\t${monthlyReturns[i]:F2}\t\t${absoluteChange:F2} ({returnType})");
157+
}
158+
159+
Console.WriteLine("-----------------------------------------------");
160+
Console.WriteLine($"Total Absolute Change: ${totalAbsoluteChange:F2}");
161+
Console.WriteLine($"Average Absolute Change: ${totalAbsoluteChange / monthlyReturns.Length:F2}");
72162
}
73163
}
74164
```
165+
166+
## Frequently Asked Questions
167+
168+
### 1. What happens if I pass a positive number to `Math.Abs()`?
169+
170+
The method returns the same positive number unchanged. For example, `Math.Abs(5)` returns 5.
171+
172+
### 2. Can `Math.Abs()` handle floating-point numbers?
173+
174+
Yes, `Math.Abs()` supports all numeric types including `float`, `double`, and `decimal`. It preserves the data type of the input.
175+
176+
### 3. What does `Math.Abs()` return for zero?
177+
178+
`Math.Abs(0)` returns 0, as the absolute value of zero is zero.
179+
180+
### 4. Can `Math.Abs()` cause overflow exceptions?
181+
182+
Yes, with certain integer types like `Int32.MinValue`, calling `Math.Abs()` can throw an `OverflowException` because the absolute value exceeds the maximum positive value for that type.

0 commit comments

Comments
 (0)