repo
stringlengths 26
115
| file
stringlengths 54
212
| language
stringclasses 2
values | license
stringclasses 16
values | content
stringlengths 19
1.07M
|
---|---|---|---|---|
https://github.com/coco33920/.files | https://raw.githubusercontent.com/coco33920/.files/mistress/typst_templates/README.md | markdown | # Typst Templates
Here, you can find the five templates that currently ship with the [Typst web
app.](https://typst.app)
This is only a temporary home for them until we have built a proper package
manager for Typst.
For community creations, also see: <https://github.com/qjcg/awesome-typst>
|
|
https://github.com/The-Notebookinator/notebookinator | https://raw.githubusercontent.com/The-Notebookinator/notebookinator/main/themes/radial/components/glossary.typ | typst | The Unlicense | #import "/utils.typ"
#let glossary = utils.make-glossary(glossary => {
columns(2)[
#for entry in glossary {
box[
== #entry.word
#entry.definition
\
]
}
]
})
|
https://github.com/jomaway/typst-gentle-clues | https://raw.githubusercontent.com/jomaway/typst-gentle-clues/main/lib/clues.typ | typst | MIT License | // gentle-clues
// Helper
#let if-auto-then(val,ret) = {
if (val == auto){
ret
} else {
val
}
}
// Global states
#let __gc_clues_breakable = state("breakable", false)
#let __gc_clues_headless = state("headless", false)
#let __gc_clue_width = state("clue-width", auto)
#let __gc_header_inset = state("header-inset", 0.5em)
#let __gc_content_inset = state("content-inset", 1em)
#let __gc_border_radius = state("border-radius", 2pt)
#let __gc_border_width = state("border-width", 0.5pt)
#let __gc_stroke_width = state("stroke-width", 2pt)
/// Config the default settings for all clues globally.
///
/// *Example:*
/// Change the default settings for all clues.
/// #figure(
/// ```typ
/// #show: gentle-clues.with(
/// headless: true, // never show any headers
/// breakable: false, // default breaking behavior
/// content-inset: 2em, // default content-inset
/// stroke-width: 6pt, // default left stroke-width
/// )
/// ```
/// )<gentle-clues-example>
///
/// - breakable (boolean): sets if clues break across pages.
/// - headless (boolean): if all clues should be shown without a header
/// - header-inset (length): sets the default header-inset for all clues.
/// - width (auto, length): sets the default width for all clues.
/// - stroke-width (length): sets the default stroke width of the left colored stroke for all clues.
/// - border-radius (length): sets the default border radius for all clues.
/// - border-width (length): sets the default border width for all clues.
/// - content-inset (length): sets the default content inset of the body for all clues.
/// - show-task-counter (boolean): enable or disable task counter for all tasks.
///
/// -> content
#let gentle-clues(
breakable: false,
headless: false,
header-inset: 0.5em,
width: auto,
stroke-width: 2pt,
border-radius: 2pt,
border-width: 0.5pt,
content-inset: 1em,
show-task-counter: false,
body
) = {
// Update breakability
__gc_clues_breakable.update(breakable);
// Update clues width
__gc_clue_width.update(width);
// Update headless state
__gc_clues_headless.update(headless);
// Update header inset
__gc_header_inset.update(header-inset);
// Update border radius
__gc_border_radius.update(border-radius);
// Update border width
__gc_border_width.update(border-width);
// Update stroke width
__gc_stroke_width.update(stroke-width);
// Update content inset
__gc_content_inset.update(content-inset);
body
}
/// Basic gentle-clue (clue) template function.
///
/// This function can be used to create custom clues. You can pass all of this parameters to the predefined clues as well to overwrite the default settings.
///
/// *Example:*
/// #example(`clue(title:"Test", width: 6cm)[Some important content]`)
/// #figure(``)<clue-api>
///
/// - content (content): Content inside the body.
/// - title (string, none): The title for the
/// - icon (none, image, symbol): The icon to show in front of the title.
/// - accent-color (color, gradient, pattern):
/// - border-color (color, gradient, pattern):
/// - header-color (color, gradient, pattern):
/// - body-color (none, color, gradient, pattern):
/// - width (auto, length):
/// - radius (auto, length):
/// - border-width (auto, length):
/// - content-inset (auto, length):
/// - header-inset (auto, length):
/// - breakable (auto, boolean):
///
/// -> content
#let clue(
content,
title: "",
icon: none,
accent-color: navy,
border-color: auto,
header-color: auto,
body-color: none,
width: auto,
radius: auto,
border-width: auto,
content-inset: auto,
header-inset: auto,
breakable: auto,
) = {
// check color types
assert(type(accent-color) in (color, gradient, pattern), message: "expected color, gradient or pattern found " + type(accent-color));
if (header-color != auto) {
assert(type(header-color) in (color, gradient, pattern), message: "expected color, gradient or pattern found " + type(header-color));
}
if (border-color != auto) {
assert(type(border-color) in (color, gradient, pattern), message: "expected color, gradient or pattern, found " + type(border-color));
}
if (body-color != none) {
assert(type(body-color) in (color, gradient, pattern), message: "expected color, gradient or pattern, found " + type(body-color));
}
context {
// Set default color:
let _stroke-color = accent-color;
let _header-color = if-auto-then(header-color, accent-color)
let _border-color = if-auto-then(border-color, accent-color)
// setting bg and stroke color from color argument
if (type(accent-color) == color) {
_header-color = if-auto-then(header-color, accent-color.lighten(85%));
_border-color = if-auto-then(border-color, accent-color.lighten(70%));
}
let _border-width = if-auto-then(border-width, __gc_border_width.get());
let _border-radius = if-auto-then(radius, __gc_border_radius.get())
let _stroke-width = if-auto-then(auto, __gc_stroke_width.get())
let _clip-content = true
// Disable Heading numbering for those headings
set heading(numbering: none, outlined: false, supplement: "Box")
// Header Part
let header = box(
fill: _header-color,
width: 100%,
radius: (top-right: _border-radius),
inset: if-auto-then(header-inset, __gc_header_inset.get()),
stroke: (right: _border-width + _header-color )
)[
#if icon == none { strong(delta:200, title) } else {
grid(
columns: (auto, auto),
align: (horizon, left + horizon),
gutter: 1em,
box(height: 1em)[ #icon
// #if type(icon) == symbol {
// text(1em,icon)
// } else if (type(icon) == str) {
// image(icon, fit: "contain")
// } else {
// icon
// }
],
strong(delta: 200, title)
)
}
]
// Content-Box
let content-box(content) = block(
breakable: if-auto-then(breakable, __gc_clues_breakable.get()),
width: 100%,
fill: body-color,
inset: if-auto-then(content-inset, __gc_content_inset.get()),
radius: (
top-left: 0pt,
bottom-left: 0pt,
top-right: if (title != none){0pt} else {_border-radius},
rest: _border-radius
),
)[#content]
// Wrapper-Block
return block(
breakable: if-auto-then(breakable, __gc_clues_breakable.get()),
width: if-auto-then(width, __gc_clue_width.get()),
inset: (left: 1pt),
radius: (right: _border-radius, left: 0pt),
stroke: (
left: (thickness: _stroke-width, paint: _stroke-color, cap: "butt"),
top: if (title != none){_border-width + _header-color} else {_border-width + _border-color},
rest: _border-width + _border-color,
),
clip: _clip-content,
)[
#set align(start)
#stack(dir: ttb,
if __gc_clues_headless.get() == false and title != none {
header
},
content-box(content)
)
] // block end
}
}
|
https://github.com/mrtz-j/typst-thesis-template | https://raw.githubusercontent.com/mrtz-j/typst-thesis-template/main/modules/supervisors.typ | typst | MIT License | #let supervisors-page(supervisors) = {
pagebreak(weak: true, to: "even")
// Apply styling to supervisor content
let supervisors-content = supervisors.map(s => {
(
[#text(weight: "semibold", s.title + ":")],
[#s.name],
[#s.affiliation],
)
})
// --- Supervisors ---
page(
numbering: none,
[
#text(
14pt,
weight: "bold",
font: ("Open Sans", "Noto Sans"),
"Supervisors",
)
#grid(
// NOTE: If supervisor title, name and affiliation overlap in the PDF, try changing the column widths here
columns: (120pt, 100pt, 200pt),
gutter: 2em,
..supervisors-content.flatten()
)
],
)
}
|
https://github.com/pride7/Typst-callout | https://raw.githubusercontent.com/pride7/Typst-callout/main/configure.typ | typst | #let logo = "images/pen.png"
#let configure = (:)
#configure.insert(
"note",
(
logo: "images/note.svg",
box-color: rgb(240, 245, 248),
title-color: rgb(88,123,207)
)
)
#configure.insert(
"summary",
(
logo: "images/summary.svg",
box-color: rgb(226, 246, 246),
title-color: rgb(70,163,162)
)
)
#configure.insert(
"question",
(
logo: "images/question.svg",
box-color: rgb(250, 239, 227),
title-color: rgb(236,117,0)
)
)
#configure.insert(
"example",
(
logo: "images/example.svg",
box-color: rgb(238, 235, 251),
title-color: rgb(120,82,238)
)
)
#configure.insert(
"quote",
(
logo: "images/quote.svg",
box-color: rgb(242, 243, 243),
title-color: rgb(155,155,155)
)
)
#configure.insert(
"warning",
(
logo: "images/warning.svg",
box-color: rgb(250, 232, 234),
title-color: rgb(233,49,71)
)
)
#configure.insert(
"check",
(
logo: "images/check.svg",
box-color: rgb(227, 246, 235),
title-color: rgb(8,185,78)
)
)
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/shape-square_03.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test text overflowing height.
#set page(width: 75pt, height: 100pt)
#square(fill: conifer)[
But, soft! what light through yonder window breaks?
]
|
https://github.com/Maso03/Bachelor | https://raw.githubusercontent.com/Maso03/Bachelor/main/Bachelorarbeit/chapters/ConvAI.typ | typst | MIT License | == ConvAI – Eine Einführung
=== Was ist ConvAI?
ConvAI ist eine fortschrittliche Plattform für Conversational AI (Künstliche Intelligenz), die speziell entwickelt wurde, um virtuelle Charaktere in Spielen und anderen virtuellen Welten mit menschlichen Kommunikationsfähigkeiten auszustatten. Die Plattform ermöglicht die Erstellung, Integration und Verwaltung von intelligenten, sprachgesteuerten Nicht-Spieler-Charakteren (NPCs), die in Echtzeit mit Nutzern interagieren können @IBMConvAI @ConvAI.
=== Funktionen und Fähigkeiten von ConvAI
In ConvAI existieren verschiedene Funktionen und Fähigkeiten, die es zu einem leistungsstarken Werkzeug für die Entwicklung von AI-gesteuerten Charakteren machen. Einige der wichtigsten Merkmale sind @NvidiaConvAI:
*1. Erstellung von Charakteren:*
Mit ConvAI können Entwickler Charaktere mit detaillierten Hintergrundgeschichten, spezifischen Stimmen und Fachwissen erstellen. Die Plattform bietet eine benutzerfreundliche Oberfläche, die es ermöglicht, diese Eigenschaften zu definieren und sofort zu testen.
*2. Integration in Spiel-Engines:*
ConvAI lässt sich nahtlos in beliebte Spiel-Engines wie Unity, Unreal Engine und ThreeJS integrieren. Dies ermöglicht es, die erstellten Charaktere direkt in die virtuellen Welten und Anwendungen zu übertragen und zu nutzen.
*3. Echtzeit-Sprachinteraktionen:*
Die Charaktere, die mit ConvAI erstellt wurden, sind in der Lage, offene sprachbasierte Konversationen zu führen und Aktionen auszuführen. Dies macht sie ideal für den Einsatz in Spielen, Lernanwendungen und anderen interaktiven Umgebungen.
*4. Wissensbasis und Expertenwissen:*
ConvAI adressiert das Problem der "Halluzination" von Informationen durch große Sprachmodelle, indem es eine Wissensbasis hinzufügt. Dies stellt sicher, dass die Charaktere genaue Antworten auf Nutzeranfragen geben können und als verlässliche Experten fungieren.
*5. Umgebungswahrnehmung und Aktionen:*
Die Charaktere können ihre Umgebung wahrnehmen und entsprechend agieren. Sie erkennen verschiedene Objekte und Entitäten in ihrer Umgebung und führen basierend auf Befehlen oder eigener Motivation Handlungen aus.
=== Technologische Integration
*1. Nutzung von NVIDIA-Technologien:*
ConvAI nutzt die NVIDIA Avatar Cloud Engine (ACE) sowie andere NVIDIA-Technologien wie Audio2Face und Riva, um realistische Gesichtsanimationen, Sprach-zu-Text- und Text-zu-Sprach-Funktionen zu ermöglichen. Diese Integration sorgt für eine niedrige Latenz und hohe Qualität bei der Animation und Interaktion der Charaktere.
*2. Erweiterung in NVIDIA Omniverse:*
Durch die Entwicklung einer Erweiterung für NVIDIA Omniverse können Benutzer ihre 3D-Charaktere mit intelligenten Konversationsagenten verbinden. Diese Erweiterung ermöglicht es, die in ConvAI erstellten Hintergrundgeschichten und Stimmen auf anpassbare 3D-Charaktere zu übertragen und mit ihnen zu interagieren.
*3. Emotionale Wahrnehmung:*
Die Charaktere von ConvAI sind in der Lage, Emotionen zu erkennen und entsprechend zu reagieren. Dies wird durch die Generierung von passenden Gesichtsausdrücken, Stimmen und Gesten erreicht, die den Charakteren eine lebendigere und realistischere Präsenz verleihen.
=== Einsatzbereiche und Vorteile von ConvAI
*1. Spieleindustrie:*
ConvAI kann genutzt werden, um intelligente Begleiterbots zu entwickeln, die komplexe Kommandos und Strategien ausführen können. Dies verbessert die Spielerfahrung durch dynamischere und realistischere NPC-Interaktionen.
*2. Bildungssektor:*
Im Bildungsbereich können AI-gesteuerte Trainingsanwendungen in verschiedenen Bereichen wie Gesundheitswesen, Recht, Fertigung und E-Commerce eingesetzt werden. Diese Anwendungen bieten personalisierte Lernunterstützung und -anweisungen.
*3. Markenagenten:*
ConvAI ermöglicht es Unternehmen, virtuelle Agenten zu erstellen, die Benutzer über Produkte und Dienstleistungen informieren. Diese Agenten können sowohl online als auch in physischen Geschäften, XR-Umgebungen und anderen öffentlichen Orten eingesetzt werden.
*4. Real-World Embodied Agents:*
In realen Umgebungen wie Geschäften, Restaurants, Büros, Einkaufszentren und Flughäfen können ConvAI-gesteuerte Agenten genutzt werden, um interaktive und informative Erlebnisse zu schaffen.
=== Zukünftige Entwicklungen und Potenzial
ConvAI treibt die Entwicklung von AI-gesteuerten Charakteren voran und öffnet die Tür für zahlreiche neue Anwendungsfälle. Die kontinuierliche Weiterentwicklung und Integration von Technologien wie NVIDIA NeMo und Triton Inference Server verspricht eine weitere Verbesserung der Reaktionsgeschwindigkeit und der Interaktivität der Charaktere.
Durch die Nutzung von ConvAI können Entwickler und Unternehmen immersive, interaktive und emotional ansprechende Charaktere erstellen, die das Nutzererlebnis in virtuellen und realen Welten revolutionieren @NvidiaConvAI. |
https://github.com/pedrofp4444/BD | https://raw.githubusercontent.com/pedrofp4444/BD/main/report/content/[6] Conclusão e Trabalhos Futuros/conclusão.typ | typst | #let conclusão = {
[
Com a implementação do sistema de gestão de base de dados, tanto Vizela como a empresa _Lusium_ aprimoraram a sua segurança em diversos aspetos, trazendo um aumento exponencial tanto nos lucros como na qualidade de vida de todos os envolvidos. A adoção deste sistema representa um passo fundamental para garantir a integridade, confidencialidade e disponibilidade de informações críticas para a resolução de casos.
Durante a execução deste projeto, tivemos o auxílio de um diagrama de Gantt para delimitar prazos a cumprir durante o seu desenvolvimento. Pontualmente, demonstramos alguma inexperiência na demarcação do tempo necessário para concluir as distintas fases do projeto. Estas inconveniências causaram algumas irregularidades no diagrama de Gantt, porém foram superadas, sem causar muitos impedimentos ao cumprimento da data final de entrega:
#align(center)[
#figure(
kind: image,
caption: "Ilustração do diagrama de Gantt real da primeira fase.",
image("../../images/Captura_GANTT_real.png", width: 100%)
)
]
De forma semelhante à execução da primeira fase do projeto, foi criado um diagrama de Gantt para planear e estipular prazos para a conclusão da implementação física. Com a nossa pequena experiência em planeamento, conseguimos produzir um diagrama de Gantt realista e exequível:
#align(center)[
#figure(
kind: image,
caption: "Ilustração do diagrama de Gantt real da segunda fase.",
image("../../images/Captura_GANTT_real2.png", width: 100%)
)
]
Manteremos continuamente contacto com a _Lusium_ para prestar serviços de manutenção e auxílio com eventuais problemas que possam surgir na base de dados. A formulação íntegra e consolidada do caso de estudo, apresentado no decorrer da produção da solução proposta, permitiu a solidificação da composição de todo o sistema, que teve por base o estrito cumprimento de todas as etapas do "ciclo de vida de uma base de dados".
]
}
|
|
https://github.com/Gekkio/gb-ctr | https://raw.githubusercontent.com/Gekkio/gb-ctr/main/chapter/cartridges/huc3.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "../../common.typ": *
== HuC-3 mapper chip
HuC-3 supports ROM sizes up to 16 Mbit (128 banks of #hex("4000") bytes), and RAM
sizes up to 1 Mbit (16 banks of #hex("2000") bytes). Like HuC-1, it includes
support for infrared communication, but also includes a real-time-clock (RTC)
and output pins used to control a piezoelectric buzzer. The information in this
section is based on my HuC-3 research.
|
https://github.com/OverflowCat/BUAA-Digital-Image-Processing-Sp2024 | https://raw.githubusercontent.com/OverflowCat/BUAA-Digital-Image-Processing-Sp2024/master/chap11/4/answer.typ | typst | #set par(leading: 1em)
== 假设
- *瓶子位置和尺寸一致*:假设瓶子不倾斜,垂直位置和尺寸大致一致。
- *图片拍摄条件一致*:假设拍摄条件一致,瓶子在传送带上的位置和角度相对固定。
- *灰度对比明显*:假设图像中瓶子和背景有明显的灰度对比,能够通过二值化处理有效区分。
- *传送带速度合适、恒定*:假设传送带的速度恒定,瓶子在传送带上的运动速度和方向一致,瓶子中液体不会摇晃。
- *整齐排列*:假设瓶子在传送带上排列整齐,水平位置和大小差异不大,便于排序和检测。
== 方案
#set enum(numbering: "1.")
1. *图像预处理*:读取灰度图像并进行二值化处理,将图像转换为黑白图,以区分瓶子和背景。
2. *形态学操作*:对二值化图像进行形态学开操作,去除图像噪声,确保瓶子轮廓清晰。
3. *连通分量分析*:使用连通分量分析技术检测瓶子位置,计算各瓶子的统计信息,如面积和位置。
4. *液位检测*:根据瓶子的高度和液面位置判断瓶子是否装满。如果液面低于设定的阈值,则认为瓶子未装满。
5. *结果显示*:在图像上标注检测结果,使用不同颜色框和编号表示检测结果。
== 实现
#show raw: set text(font: "Sarasa Term Slab SC", size: 1.08em)
=== 图像预处理与二值化
```python
gray_image = cv2.imread("bottles-assembly-line.tif", 0) # 0 表示以灰度模式读取
BW_THRESHOLD = 170 # 二值化阈值
_, binary_image = cv2.threshold(gray_image, BW_THRESHOLD, 255, cv2.THRESH_BINARY)
```
读取灰度图像,并使用阈值170进行二值化处理,将图像转换为黑白图。
=== 形态学操作
```python
kernel = np.ones((3, 7), np.uint8)
opened_image = cv2.morphologyEx(binary_image, cv2.MORPH_OPEN, kernel)
```
使用形态学开操作去除噪声,确保瓶子的轮廓更加清晰。若不进行形态学操作,可能会导致连通分量分析不准确,如@bottles_notopen 所示。
#figure(caption: "未进行形态学开操作,直接处理的结果", image("./colored.png", width: 7cm))<bottles_notopen>
=== 连通分量分析
```python
num_labels, labels_im, stats, centroids = cv2.connectedComponentsWithStats(opened_image)
```
使用 ```python cv2.connectedComponentsWithStats``` 获取连通分量及其统计信息。
=== 液位检测与结果显示
```python
AREA_THRESHOLD = 900 # 面积阈值
components = [
stats[i]
for i in range(1, num_labels)
if stats[i, cv2.CC_STAT_AREA] > AREA_THRESHOLD
]
components.sort(key=lambda x: x[cv2.CC_STAT_LEFT]) # 按水平位置排序
for i, component in enumerate(components):
x, y, width, height, area = component
bottom = y + height
is_full = bottom < 100 # 液面阈值
color = (0, 255, 0) if is_full else (0, 0, 255) # 满的为绿色,未满的为红色
cv2.rectangle(output_image, (x, y), (x + width, y + height), color, 2)
cv2.putText(output_image, f"{i + 1}", (x, y + height + 25), cv2.FONT_HERSHEY_SIMPLEX, 0.75, color, 2, cv2.LINE_AA)
```
根据连通分量的面积和位置筛选出有效的瓶子,计算液面位置,判断是否装满,并在图像上绘制矩形框和编号。液面低于100像素认为瓶子未装满,用红色框表示;否则用绿色框表示。
=== 结果输出
最终输出图片结果如@bottles_out 所示。
#figure(caption: "检测结果", image("./output.png", width: 9cm))<bottles_out>
控制台输出结果如下:
```shell
第 0 个连通分量的面积为 2607,高度为 65,液面位置的 y 坐标为 83,是满的
第 1 个连通分量的面积为 3132,高度为 63,液面位置的 y 坐标为 81,是满的
第 2 个连通分量的面积为 8606,高度为 119,液面位置的 y 坐标为 136,不是满的
第 3 个连通分量的面积为 3132,高度为 63,液面位置的 y 坐标为 81,是满的
第 4 个连通分量的面积为 1871,高度为 65,液面位置的 y 坐标为 83,是满的
```
通过以上方法,能够有效检测传送带上未完全装满液体的瓶子,并在图像上直观展示检测结果。
#"\n"
#"\n"
#"\n"
#"\n"
== 附:程序完整代码
#set par(leading: .85em)
#let file = read("./bottles.py")
#raw(file, lang: "python")
|
|
https://github.com/deadManAlive/ui-thesis-typst-template | https://raw.githubusercontent.com/deadManAlive/ui-thesis-typst-template/master/config.typ | typst | #let cfg = (
title : lorem(20),
name : "Mulyanto",
npm : "19650931",
faculty : "Fakultas Teknik",
program : "Teknik Elektro",
location : "Lubang Buaya",
time : "Agustus 2024",
degree : "Sarjana Teknik",
advisors : (
"Dr. Doom",
"Dr. Strange",
),
examiners: (
"Mr. Mr.",
"<NAME>"
)
) |
|
https://github.com/mariunaise/HDA-Thesis | https://raw.githubusercontent.com/mariunaise/HDA-Thesis/master/graphics/quantizers/s-metric/3_2_reconstruction.typ | typst | #import "@preview/cetz:0.2.2": canvas, plot
#let line_style = (stroke: (paint: red, thickness: 2pt))
#let line_style2 = (stroke: (paint: blue, thickness: 2pt))
#let line_style3 = (stroke: (paint: green, thickness: 2pt))
#let dashed = (stroke: (dash: "dashed"))
#canvas({
plot.plot(size: (8,6),
legend: "legend.south",
legend-style: (orientation: ltr, item: (spacing: 0.5)),
x-tick-step: 1/4,
//x-ticks: ((3/16, [3/16]), (7/16, [7/16]), (11/16, [11/16]), (15/16, [15/16])),
y-label: $cal(R)(3, 2, tilde(x))$,
x-label: $tilde(x)$,
y-tick-step: none,
y-ticks: ((1/4, [00]), (2/4, [01]), (3/4, [10]), (1, [11])),
axis-style: "left",
x-min: 0,
x-max: 1,
y-min: 0,
y-max: 1,{
plot.add(((0, 1/4), (5/24, 1/4), (11/24, 2/4), (17/24, 3/4), (23/24, 1), (23/24, 1/4), (1, 1/4)),line: "vh", style: line_style, label: [Metric 1])
plot.add(((0,1/4), (1/4,1/4), (2/4,2/4), (3/4,3/4), (4/4, 4/4)), line: "vh", style: line_style2, label: [Metric 2])
plot.add(((0, 1),(1/24, 1), (1/24, 1/4), (7/24, 1/4), (7/24, 2/4), (13/24, 3/4), (19/24, 1), (1, 1)), line: "hv", style: line_style3, label: [Metric 3])
plot.add-hline(1/4, 2/4, 3/4, 1, style: dashed)
plot.add-vline(1/4, 2/4, 3/4, 1, style: dashed)
})
})
|
|
https://github.com/daxartio/cv | https://raw.githubusercontent.com/daxartio/cv/main/en.typ | typst | MIT License | #import "cv.typ": cv
#cv("en.yml")
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/layout/enum.typ | typst | Apache License 2.0 | // Test enumerations.
---
#enum[Embrace][Extend][Extinguish]
---
0. Before first!
1. First.
2. Indented
+ Second
---
// Test automatic numbering in summed content.
#for i in range(5) {
[+ #numbering("I", 1 + i)]
}
---
// Mix of different lists
- Bullet List
+ Numbered List
/ Term: List
---
// In the line.
1.2 \
This is 0. \
See 0.3. \
---
// Edge cases.
+
Empty \
+Nope \
a + 0.
---
// Test item number overriding.
1. first
+ second
5. fifth
#enum(
enum.item(1)[First],
[Second],
enum.item(5)[Fifth]
)
|
https://github.com/NMD03/typst-uds | https://raw.githubusercontent.com/NMD03/typst-uds/main/README.md | markdown |
# Typst template for Saarland University
This template is based on a [DHBW Template](https://github.com/C0ffeeCode/typst-dhbw-technik-template.git) by [@C0ffeeCode](https://github.com/C0ffeeCode).
As an example and guide how to use this template,
check out [this PDF document](./Template-Example-guide.pdf).
|
|
https://github.com/coco33920/.files | https://raw.githubusercontent.com/coco33920/.files/mistress/typst_templates/statuts/template.typ | typst | #let template(
//nom de l'association
name: none,
//objet de l'association
object: none,
//adresse de l'association
address: none,
//date
date: none,
//taille du CA
size_ca: none,
//durée du mandat
duree_mandat: none,
body
) = {
let c = counter("titre")
let k = counter("articles")
set page(
numbering: "1",
number-align: right,
margin: 1in
)
align(center)[
#set text(weight: "regular", size: 20pt)
#v(40%)
#name - Statuts\
#v(0.5em)
#set text(size: 14pt)
Association déclarée par application de la loi du 1er juillet 1901 et du décret du 16 août 1901.
]
if(date != none) {
set align(center)
v(1em)
date
}
pagebreak(weak: true)
set align(left)
show heading.where(level: 1): it => block(width: 100%)[
#c.step()
#set align(center)
#set text(12pt, weight: "bold")
Titre #c.display("I") \
#it.body
]
show heading.where(level: 2): it => block[
#k.step()
#set text(12pt, weight: "regular")
#smallcaps([Article ]) #k.display().
#smallcaps(it.body)
]
set text(10pt,weight: "regular")
set par(justify: true)
body
} |
|
https://github.com/arthurcadore/eng-telecom-workbook | https://raw.githubusercontent.com/arthurcadore/eng-telecom-workbook/main/semester-7/COM_1/homework6/homework.typ | typst | MIT License | #import "@preview/klaro-ifsc-sj:0.1.0": report
#import "@preview/codelst:2.0.1": sourcecode
#show heading: set block(below: 1.5em)
#show par: set block(spacing: 1.5em)
#set text(font: "Arial", size: 12pt)
#show: doc => report(
title: "Atividade Extra",
subtitle: "Sistemas de Comunicação I",
authors: ("<NAME>",),
date: "30 de Junho de 2024",
doc,
)
= Questão 1:
== Realize os seguintes procedimentos:
- 1. Gerar uma sequência de bits aleatórios
#sourcecode[```matlab
pkg load signal;
% quantidade de bits que serão gerados;
num_bits = 1000;
% Gerando bits aleatórios com rand inteiro;
bits = randi([0 1], 1, num_bits);
```]
- 2. Mapear a sequência de bits para símbolos utilizando uma sinalização 4-PAM.
#sourcecode[```matlab
% Mapeamento dos bits para símbolos 4-PAM
% Para esse mapeamento utilizei a seguinte lógica:
% 00 -> -3
% 01 -> -1
% 11 -> 1
% 10 -> 3
symbols = zeros(1, num_bits/2);
for i = 1:2:num_bits
if bits(i) == 0 && bits(i+1) == 0
symbols((i+1)/2) = -3;
elseif bits(i) == 0 && bits(i+1) == 1
symbols((i+1)/2) = -1;
elseif bits(i) == 1 && bits(i+1) == 1
symbols((i+1)/2) = 1;
else
symbols((i+1)/2) = 3;
end
end
```]
- 3. Aplicar o filtro cosseno levantado com um fator de roll-off especificado (r) e uma taxa de amostragem adequada.
#sourcecode[```matlab
% Parâmetros do filtro cosseno levantado
roll_off = 0.25;
% Taxa de amostragem
fs = 8
% Duração do filtro;
T = 6;
% Gerando o vetor de tempo;
t = -T/2:1/fs:T/2;
% Geração do filtro cosseno levantado
h = (sin(pi*t*(1-roll_off)) + 4*roll_off*t.*cos(pi*t*(1+roll_off))) ./ (pi*t.*(1-(4*roll_off*t).^2));
h(t==0) = (1-roll_off)+4*roll_off/pi;
h(abs(t)==1/(4*roll_off)) = roll_off/sqrt(2)*((1+2/pi)*sin(pi/(4*roll_off)) + (1-2/pi)*cos(pi/(4*roll_off)));
% Aumentando a quantidade de Amostras com o upsample para normalizar a taxa de amostragem
upsampled_symbols = upsample(symbols, fs);
filtered_signal = conv(upsampled_symbols, h, 'same');
```]
- 4. Plotar a forma de onda resultante no domínio do tempo.
#sourcecode[```matlab
% Plot da forma de onda no domínio do tempo
figure;
subplot(2,1,1);
plot(filtered_signal);
title('Forma de Onda no Domínio do Tempo');
xlabel('Amostras');
ylabel('Amplitude');
```]
- 5. Calcular e plotar a densidade espectral de potência do sinal filtrado.
#sourcecode[```matlab
% Cálculo e plot da densidade espectral de potência
[pxx, f] = pwelch(filtered_signal, [], [], [], fs);
subplot(2,1,2);
plot(f-pi,10*log10(fftshift(pxx)));
title('Densidade Espectral de Potência');
xlabel('Frequência Normalizada');
ylabel('Densidade Espectral de Potência');
```]
#figure(
figure(
rect(image("./pictures/q1.png")),
numbering: none,
caption: [Forma de onda no domínio do tempo e densidade espectral de potência do sinal filtrado.]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
== Responda as questões:
- Qual o efeito do fator de roll-off na forma de onda do sinal e na densidade espectral de potência?
O fator de roll-off afeta a forma de onda do sinal deixando ele mais suavisado ou variando mais drasticamente. Um exemplo claro dessa diferença é uma onda senoidal (onde a trasição é a mais suave possivel ou em uma onda quadrada (onde a transição é a mais rápida possível entre o valor negativo e positivo).
Quanto menor o roll-off, mais proximo de uma onda quadrada, ou seja, com transições rápidas a onda se torna, isso melhora sua eficiência no espectro, pois concentra sua potência em uma determinada região.
- Como a taxa de amostragem afeta a qualidade da formatação do sinal?
A taxa de amostragem afeta diretamente a qualidade da formatação do sinal, pois quanto maior a taxa de amostragem, mais amostras do sinal são coletadas e mais detalhes do sinal são amostrados.
Isso é muito importante para garantir que o sinal seja corretamente amostrado e que não haja perda de informações importantes. Caso a taxa de amostragem seja muito baixa, o sinal pode ser subamostrado (ou seja, tão poucas amostras que o sinal não pode ser compreendido no receptor) e informações importantes podem ser perdidas.
= Questão 2:
Responda as seguintes perguntas:
== Item 1:
Explique o princípio de operação de um filtro casado e sua importância na detecção de sinais.
O filtro casado é um filtro que é projetado para maximizar a relação sinal-ruído (SNR) na saída do receptor para um determinado tipo de sinal.
Ele é projetado para ser o filtro que melhor se adapta ao sinal transmitido, ou seja, em uma transmissão FM por exemplo, podemos utilizar um filtro que "copie" de certa maneira as caracteristicas de transmissão que o sinal poderá ter, sua largura no espectro, formato de transmissão, componente da onda que irá variar (no caso do FM a frequência) de forma a maximizar a SNR para esse tipo de sinal.
== Item 2:
Quais são as vantagens e desvantagens de aumentar o número de níveis M em M-PAM?
A principal vantagem em aumentar o número de níveis M em M-PAM é que a eficiência espectral do sistema aumenta, ou seja, é possivel mandar mais informação pelo meio de transmissão a partir de uma mesma "região do espectro"
Isso é possivel pois a quantidade de bits transmitidos por símbolo aumenta mas sem aumentar o consumo do espectro, o que permite transmitir mais informações em um determinado intervalo de tempo.
Por outro lado, a principal desvantagem de aumentar o número de níveis M em M-PAM é que a sensibilidade do sistema ao ruído aumenta e também é muito mais dificil implementar o circuito de transmissão/recepção para operar com uma densidade de simbolos mais alta, ou seja, quanto mais níveis M, mais sensível o sistema se torna ao ruído, o que pode levar a uma maior probabilidade de erro de bit.
Um exemplo de transmissão que aumenta a densidade mas não necessáriamente possui desvantagem na recepção é passar de FDM para OFDM, onde ao adicionar uma componente de transmissão ortogonal aumentamos a quantidade de portadoras para a transmissão mas sem necessáriamente aumentar a sensibilidade ao ruído.
== Item 3:
Defina o Pulso Ideal de Nyquist e descreva suas propriedades principais.
O pulso de Nyquist é um pulso que é projetado para ser o mais eficiente possível em termos de eficiência espectral, ou seja, ele é projetado para maximizar a quantidade de informação transmitida por um determinado intervalo de tempo.
Esse pulso é utilizado para servir de base para a transmissão de sinais digitais, pois ele é capaz de transmitir a maior quantidade de informação possível em um determinado intervalo de tempo, sem que haja interferência entre os símbolos transmitidos.
== Item 4:
Explique o que é a Inter-Symbol Interference (ISI) e como ela afeta a performance de um sistema de comunicação digital
A interferência entre simbolos é um problema que ocorre quando um símbolo transmitido interfere com o símbolo seguinte, ou seja, quando a transmissão de um símbolo não é completamente finalizada antes que o próximo símbolo seja transmitido.
Isso pode ocorrer devido a diversos fatores, como atrasos na transmissão, reflexões do sinal, interferência de outros sinais, entre outros.
Para evitar esse problema em redes wi-fi por exemplo é utilizado um parâmetro denominado GI ou intervalo de guarda, para evitar que um símbolo interfira no próximo.
= Questão 3:
== Item 3.10:
Dados binários a 9600 bits/s são transmitidos usando modulação PAM 8-ária com um sistema usando uma característica de filtro de decaimento cosseno levantado. O sistema tem uma resposta
em frequência de até 2.4 kHz.
- Qual a taxa de símbolos do sistema?
$
log_2(8)=3
$
Desta forma, temos que `3` é a quantidade de bits utilizada.
$
R_s = 9600/3 = 3200 #text("simbolos/s")
$
- Qual é o fator de decaimento da característica do filtro?
$
2.4"kHz" = (1 + alpha) * R_s
1 + alpha = (2.4 * 10^3) / 3200
$
$
1 + alpha = 0.75 = alpha = -0.25
$
Encontrando alfa, podemos determinar o valor de beta através da seguinte equação:
$
beta = 1/alpha = beta = 1/(-0.25) = -4
$
== Item 3.14:
Considere que pulsos binários NRZ são transmitidos ao longo de um cabo que atenua a potência do sinal em 3 dB (do transmissor para o receptor). Os pulsos são detectados coerentemente no receptor, e a taxa de dados é de 56 kbit/s. Suponha ruído Gaussiano com $N_0$ = $10^(−6)$ Watt/Hz. Qual é a quantidade mínima de potência necessária no transmissor para manter uma probabilidade de erro de bit de Pb = $10^(−3)$? A capacidade do canal é dada por:
$
C = B * log_2(1 + "SNR")
$
Dados do problema:
- 56Kbps = B = R
- $P_("TX")$ = $P_("RX") - 3"dB"$
Desta forma temos que:
$
56 * 10^3 = 56 * 10^3 * log_2(1 + "SNR")
$
$
56 * 10^3 = 56 * 10^3 * log_2(1 + P/(2 * 10^(-6)))
$
$
1 = log_2(1 + P/(2 * 10^(-6)))
$
$
2 = 1 + P / (2 * 10^(-6))
$
$
1 = P / (2 * 10^(-6))
$
Portanto temos que a potência mínima necessária é de $2 * 10^(-6)$ Watt.
= Referências Bibliográficas
Para o desenvolvimento deste relatório, foi utilizado o seguinte material de referência:
- #link("https://www.researchgate.net/publication/287760034_Software_Defined_Radio_using_MATLAB_Simulink_and_the_RTL-SDR")[Software Defined Radio Using MATLAB & Simulink and the RTL-SDR, de <NAME>. Stewart]
|
https://github.com/dismint/docmint | https://raw.githubusercontent.com/dismint/docmint/main/biology/lec3.typ | typst | #import "template.typ": *
#show: template.with(
title: "Lecture 3",
subtitle: "7.016"
)
= Amino Acids
#define(
title: "Amino Acid"
)[
An amino acid is a protein that contains both the amino as well as carboxylic acid groups.
]
In the context of an amino acid, $R$ is the side chain, and is what distinguishes an amino acid. The middle Carbon is called an $alpha$-Carbon.
Two amino acids bind together in what is called a condensation reaction, where you lose a Hydrogen and Oxygen from one molecule, and another Hydrogen from the other, to make a water.
#define(
title: "Peptide Bond"
)[
A peptide bond is the resulting middle section that forms from a condensation reaction, and consists of:
$ "H-N-C=O" $
]
= Amino Acid Groups (Side Chains)
The chart of 20 / 21 amino acids is completely based off of the $R$ group. They are encoded into the non-polar, polar, (+) charge, and (-) charge groups.
There are several ways to recognize each group
/ Non-polar: Loose ends of carbon, which is why it is non-polar.
/ Polar: Hanging groups, making it polar
/ (+) Charge: Has a (+) icon.
/ (-) Chage: Has a (-) icon.
= Levels of Protein Structures
There are four levels of protein structure: Primary, Secondary, Tertiary, and Quaternary.
#define(
title: "Primary Structure"
)[
A *sequence* of amino acids from a Nitrogen-terminus to a Carbon-terminus. It *must* be read from the N to C terminus. Peptide (covalent) bonds bold the primary structure.
]
#define(
title: "Secondary Structure"
)[
There are three primary types:
- $alpha$-helix
- $beta$-sheet
- Loop / Turn
Hydrogen bonds bold the structure together.
]
#define(
title: "Tertiary Structure"
)[
/ Side Chain - Side Chain: Disulfide Bond, Ionic Bond, Hydrogen Bond, Hydrophobic Interaction.
/ Side Chain - Peptide Backbone: Hydrogen Bond.
/ Side Chain - Water: Hydrogen Bond.
]
#define(
title: "Quaternary Structure"
)[
Quaternary structures are a description of the number, type, and arrangement of polypeptide chains.
/ Number: Monomer, Dimer, Trimer, Tetramer
/ Identity: Identical (Homo), (Different) (Hetero)
For the number, if there are two similar types, it only counts as one. For example, two $alpha$ peptides and two *distinct* $beta$ peptides make a *Hetero Trimer*.
The interactions are the same as the tertiary structures.
]
|
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/027_Conspiracy%3A%20Take%20the%20Crown.typ | typst | #import "@local/mtgset:0.1.0": conf
#show: doc => conf("Conspiracy: Take the Crown", doc)
#include "./027 - Conspiracy: Take the Crown/001_Laid to Rest.typ"
#include "./027 - Conspiracy: Take the Crown/002_Tyrants.typ"
#include "./027 - Conspiracy: Take the Crown/003_Proclamation by Queen Marchesa.typ"
#include "./027 - Conspiracy: Take the Crown/004_Proclamation by Adriana, Captain of the Guard.typ"
#include "./027 - Conspiracy: Take the Crown/005_Bloody Instructions.typ"
#include "./027 - Conspiracy: Take the Crown/006_Leovold's Dossiers.typ"
|
|
https://github.com/Iskander000/lab4 | https://raw.githubusercontent.com/Iskander000/lab4/main/Lab-4.typ | typst | #import "Class.typ": *
#show: ieee.with(
title: [#text(smallcaps("Lab #4: ROS2 using RCLPY in Julia"))],
/*
abstract: [
#lorem(10).
],
*/
authors:
(
(
name: "<NAME>",
department: [Senior-lecturer, Dept. of EE],
organization: [ISET Bizerte --- Tunisia],
profile: "a-mhamdi",
),
(
name: "<NAME>",
department: [Dept. of EE],
organization: [ISET Bizerte --- Tunisia],
profile: "Iskander000",
),
/*
(
name: "<NAME>",
department: [Dept. of EE],
organization: [ISET Bizerte --- Tunisia],
profile: "abc",
),
(
name: "Student 3",
department: [Dept. of EE],
organization: [ISET Bizerte --- Tunisia],
profile: "abc",
)
*/
)
// index-terms: (""),
// bibliography-file: "Biblio.bib",
)
You are required to carry out this lab using the REPL as in @fig:repl.
#figure(
image("Images/REPL.png", width: 100%, fit: "contain"),
caption: "Julia REPL"
) <fig:repl>
=== instructions :
We begin first of all by sourcing our ROS2 installation as follows:
```zsh
source /opt/ros/humble/setup.zsh
```
- then we need to open the subscriber and the publisher programmes in two different terminal
#let publisher=read("../Codes/ros2/publisher.jl")
#let subscriber=read("../Codes/ros2/subscriber.jl")
#raw(publisher, lang: "julia")
#footnote[Remember to source ROS2 installation before using it with Julia]
#raw(subscriber, lang: "julia")
- In a newly opened terminal, the exucation will show to us that the subscriber listens to the messages being broadcasted by our previous publisher and respond by a massage
to do that we need first of all to create a nodes called subscriber and publisher
```julia
# Create publisher node
node = rclpy.create_node("my_publisher")
rclpy.spin_once(node, timeout_sec=1)
# Create subscriber node
node = rclpy.create_node("my_subscriber")
```
to link the two talker and the heard to a specific topic like here we choose *infodev* as a topic like showing the graph
```julia
pub = node.create_publisher(str.String, "infodev", 10)
# Create a ROS2 subscription
sub = node.create_subscription(str.String, "infodev", callback, 10)
```
- The graphical tool *rqt_graph* of @fig:rqt_graph displays the flow of data between our nodes: #emph[my_publisher] and #emph[my_subscriber], through the topic we designed _infodev_
#figure(
image("Images/rqt_graph.png", width: 100%),
caption: "rqt_graph"
) <fig:rqt_graph>
- after linked publisher / subscriber together and then to a specifique topic the execution terminal will show us what in fig 3
#figure(
image("Images/pub-sub.png", width: 100%),
caption: "Minimal publisher/subscriber in ROS2",
) <fig:pub-sub>
- to change the message or the number of the messages prodcasted or respondet we can use this line
```julia
# Publish the message `txt`
for i in range(1, 100)
msg = str.String(data="Hello, ROS2 from Julia! ($(string(i)))")
pub.publish(msg)
txt = "[TALKER] " * msg.data
@info txt
sleep(1)
end
# Callback function to process received messages
function callback(msg)
txt = "[LISTENER] I heard: " * msg.data
@info txt
end
```
- if you haad a problem in the topic wich one you shoul use you can check from the topic list by right down this line
```zsh
source /opt/ros/humble/setup.zsh
ros2 topic list -t
```
@fig:topic-list shows the current active topics, along their corresponding interfaces.
#figure(
image("Images/topic-list.png", width: 100%),
caption: "List of topics",
) <fig:topic-list>
//#test[Some test]
|
|
https://github.com/amomorning/curriculum-vitae | https://raw.githubusercontent.com/amomorning/curriculum-vitae/main/template.typ | typst | #import "@preview/fontawesome:0.2.1": *
#let resume(
name: "<NAME>",
first-name: "John",
last-name: "Doe",
phone: "(+1) 111-111-1111",
email: "<EMAIL>",
address: "Nanjing sss",
date: datetime.today().display(),
font: ("Source Sans Pro", "Source Sans 3", "Microsoft YaHei"),
heading-font: ("Microsoft YaHei"),
color: rgb("#728497"),
body
) = {
set page(
paper: "a4",
margin: (left: 15mm, right: 15mm, top: 10mm, bottom: 10mm),
footer: [
#set text(
fill: gray,
size: 8pt,
)
#grid(columns:(1fr, 1fr, 1fr),
smallcaps[#date],
align(center)[
#smallcaps[#first-name #last-name #sym.dot.c Resume]
],
align(right)[
#counter(page).display()
]
)
],
footer-descent: 0pt,
)
// set paragraph spacing
show par: set block(
above: 0.75em,
below: 0.75em,
)
set par(justify: true)
set heading(
numbering: none,
outlined: false,
)
show heading.where(level: 1): it => [
#set block( above: 2em, below: 1em,)
#set text( font: heading-font, size: 16pt, weight: "bold")
#align(left)[
#text[#strong[#text(color)[#it.body.text]]]
#box(width: 1fr, line(length: 100%))
]
]
show heading.where(level: 2): it => {
set text(
font: heading-font,
size: 12pt,
style: "normal",
weight: "bold",
)
it.body
}
show heading.where(level: 3): it => {
set text(
size: 10pt,
weight: "regular",
)
smallcaps[#it.body]
}
set text(font: font, size: 11pt)
grid(columns: (auto, 1fr, auto),
[
#block(below: 2em)[ ]
#strong[#text(fill: color, size: 20pt)[#name]]
#block(below: 1.5em)[
#strong[#text(fill: black, size: 16pt)[#first-name]]
#strong[#text(fill: color, size: 16pt)[#last-name]]
]
#phone #sym.space #sym.dot.c #sym.space #email
#address
],[],[
#show image: it => block(
radius: 120pt, clip: true
)[#it]
#image("imgs/photo.jpg", width: 120pt)
]
)
body
}
#let resume-entry(
title: none,
location: "",
date: "",
description: "",
) = {
set block(
below: 0.7em,
)
grid(columns: (auto, 1fr, auto),
[== #title], [],
[#text(size: 10pt, weight: "regular")[#location]]
)
grid(columns: (auto, 1fr, auto),
[=== #description], [],
[#text(size: 9pt, weight: "thin")[#date]]
)
}
#let list-entry(left, right) = {
set block(
below: 0.7em,
)
grid(columns: (1fr, 7fr),
text(weight: "bold")[#left],
right
)
}
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/hydra/0.3.0/src/lib.typ | typst | Apache License 2.0 | #import "/src/core.typ"
#import "/src/util.typ"
#import "/src/selectors.typ"
/// An anchor used to search from. When using `hydra` ouside of the page header, this should be
/// placed inside the pge header to find the correct searching context. `hydra` always searches from
/// the last anchor it finds, if and only if it detects that it is outside of the top-margin.
#let anchor() = [#metadata(()) <hydra-anchor>]
/// Query for an element within the bounds of its ancestors.
///
/// The context passed to various callbacks contains the resolved top-margin, the current location,
/// as well as the binding direction, primary and ancestor element selectors and customized
/// functions.
///
/// - ..sel (any): The element to look for, to use other elements than headings, read the
/// documentation on selectors. This can be an element function or selector, an integer declaring
/// a heading level.
/// - prev-filter (function): A function which receives the `context` and `candidates`, and returns
/// if they are eligible for display. This function is called at most once. The primary next
/// candidate may be none.
/// - next-filter (function): A function which receives the `context` and `candidates`, and returns
/// if they are eligible for display. This function is called at most once. The primary prev
/// candidate may be none.
/// - display (function): A function which receives the `context` and candidate element to display.
/// - skip-starting (bool): Whether `hydra` should show the current candidate even if it's on top of
/// the current page.
/// - book (bool): The binding direction if it should be considered, `none` if not. If the binding
/// direction is set it'll be used to check for redundancy when an element is visible on the last
/// page. Make sure to set `binding` and `dir` if the document is not using left-to-right reading
/// direction.
/// - binding (alignment): The binding direction of the document.
/// - dir (direction): The reading direction, that is, the direction pages are read in, this is
/// usually the same as the text direction, but doesn't have to be.
/// - paper (str): The paper size of the current page, used to calculate the top-margin.
/// - page-size (length, auto): The smaller page size of the current page, used to calculated the
/// top-margin.
/// - top-margin (length, auto): The top margin of the current page, used to check if the current
/// page has a primary candidate on top.
/// - anchor (label, none): The label to use for the anchor if `hydra` is used outside the header.
/// If this is `none`, the anchor is not searched.
/// - loc (location, none): The location to use for the callback, if this is not given `hydra` calls
/// locate internally, making the return value opaque.
/// -> content
#let hydra(
prev-filter: (ctx, c) => true,
next-filter: (ctx, c) => true,
display: core.display,
skip-starting: true,
book: false,
binding: left,
dir: ltr,
paper: "a4",
page-size: auto,
top-margin: auto,
anchor: <hydra-anchor>,
loc: none,
..sel,
) = {
util.assert.types("prev-filter", prev-filter, function)
util.assert.types("next-filter", next-filter, function)
util.assert.types("display", display, function)
util.assert.types("skip-starting", skip-starting, bool)
util.assert.types("book", book, bool)
util.assert.enum("binding", binding, left, right)
util.assert.enum("dir", dir, ltr, rtl)
util.assert.types("paper", paper, str)
util.assert.types("page-size", page-size, length, auto)
util.assert.types("top-margin", top-margin, length, auto)
util.assert.types("anchor", anchor, label, none)
util.assert.types("loc", loc, location, none)
// if margin is auto we need the page size
if top-margin == auto {
// if page size is auto then only paper was given
if page-size == auto {
if paper == auto {
panic("Must set one of `paper`, `page-size` or `top-margin`")
}
page-size = util.page-sizes.at(paper, default: none)
assert.ne(page-size, none, message: util.fmt("Unknown paper: `{}`", paper))
page-size = calc.min(page-size.w, page-size.h)
}
// the calculation given by page.margin's documentation
top-margin = (2.5 / 21) * page-size
}
let (named, pos) = (sel.named(), sel.pos())
assert.eq(named.len(), 0, message: util.fmt("Unexected named arguments: `{}`", named))
assert(pos.len() <= 1, message: util.fmt("Unexpected positional arguments: `{}`", pos))
let sanitized = selectors.sanitize("sel", pos.at(0, default: heading))
let func = loc => {
let ctx = (
prev-filter: prev-filter,
next-filter: next-filter,
display: display,
skip-starting: skip-starting,
book: book,
binding: binding,
dir: dir,
top-margin: top-margin,
anchor: anchor,
loc: loc,
primary: sanitized.primary,
ancestors: sanitized.ancestors,
)
core.execute(ctx)
}
if loc != none {
func(loc)
} else {
locate(func)
}
}
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/in-dexter/0.1.0/in-dexter.typ | typst | Apache License 2.0 | // Copyright 2023 <NAME>, <NAME>
// Use of this code is governed by the License in the LICENSE.txt file.
// For a 'how to use this package', see the accompanying .md, .pdf + .typ documents.
// Adds a new entrty to the index
// @param fmt: function: content -> content
// @param initial: "letter" to sort entries under - otherwise first letter of entry is used,
// useful for indexing umlauts or accented letters with their unaccented versions or
// symbols under a common "Symbols" headline
// @param ..entry, variable argument to nest index entries (left to right)
#let index(fmt: it => it, initial: none, ..entry) = locate(loc => [
#metadata((
fmt: fmt,
initial: initial,
location: loc.position(),
entry: entry,
))<jkrb_index>
])
// Default function to semantically mark main entries in the index
#let index-main = index.with(fmt:strong)
// Extracts (nested) content or text to content
#let as-text(input) = {
if type(input) == str {
input
} else if type(input) == content {
if input.has("text") {
input.text
} else if input.has("children") {
input.children.map(child => as-text(child)).join("")
} else if input.has("body") {
as-text(input.body)
} else {
panic("Encountered content without 'text' or 'children' field: " + repr(input))
}
} else {
panic("Unexpected entry type " + type(input) + " of " + repr(input))
}
}
// Internal function to set plain and nested entries
#let make-entries(entries, page-link, reg-entry) = {
let (entry, ..rest) = entries
if rest.len() > 0 {
let nested-entries = reg-entry.at(entry, default: (:))
let ref = make-entries(rest, page-link, nested-entries.at("nested", default: (:)))
nested-entries.insert("nested", ref)
reg-entry.insert(entry, nested-entries)
} else {
let pages = reg-entry.at(entry, default: (:)).at("pages", default: ())
if not pages.contains(page-link) {
pages.push(page-link)
reg-entry.insert(entry, ("pages": pages))
}
}
reg-entry
}
// Internal function to collet plain and nested entries into the index
#let references(loc) = {
let register = (:)
let initials = (:)
for indexed in query(<jkrb_index>, loc) {
let (entry, fmt, initial, location) = indexed.value
let entries = entry.pos().map(as-text)
if entries.len() == 0 {
panic("expected entry to have at least one entry to add to the index")
} else {
let initial-letter = if initial == none {
let first-letter = entries.first().first()
initials.insert(first-letter, first-letter)
first-letter
} else {
if (type(initial) == dictionary) {
let letter = initial.at("letter")
let sort-by = initial.at("sort-by", default: letter)
initials.insert(sort-by, letter)
letter
} else if (type(initial) == string) {
let first-letter = initial.first()
initials.insert(first-letter, first-letter)
} else {
panic("Expected initial to be either a 'string' or '(letter: <string>, sort-by: <none|string>)'")
}
}
let reg-entry = register.at(initial-letter, default: (:))
register.insert(initial-letter, make-entries(entries, (page: location.page, fmt: fmt), reg-entry))
}
}
(register: register, initials: initials)
}
// Internal function to format a page link
#let render-link((page, fmt)) = {
link((page: page, x: 0pt, y: 0pt), fmt[#page])
}
// Internal function to format a plain or nested entry
#let render-entry(idx, entries, lvl) = {
let pages = entries.at("pages", default: ())
let rendered-pages = [
#box(width: lvl * 1em)#idx#box(width: 1fr)#pages.map(render-link).join(", ") \
]
let sub-entries = entries.at("nested", default: (:))
let rendered-entries = if sub-entries.keys().len() > 0 [
#for entry in sub-entries.keys().sorted() [
#render-entry(entry, sub-entries.at(entry), lvl + 1)
]
]
[
#rendered-pages
#rendered-entries
]
}
// Inserts the index into the document
// @param title (default: none) sets the title of the index to use
// @param outlined (default: false) if index is shown in outline (table of contents)
#let make-index(title: none, outlined: false) = locate(loc => {
let (register, initials) = references(loc)
if title != none {
heading(
outlined: outlined,
numbering: none,
title
)
}
for initial in initials.keys().sorted() {
let letter = initials.at(initial)
heading(level: 2, numbering: none, outlined: false, letter)
let entry = register.at(letter)
for idx in entry.keys().sorted() {
render-entry(idx, entry.at(idx), 0)
}
}
})
|
https://github.com/kdog3682/typkit | https://raw.githubusercontent.com/kdog3682/typkit/main/0.1.0/src/resolve.typ | typst | #import "is.typ": *
#import "strokes.typ"
#import "fills.typ"
#import "alignments.typ"
#import "@preview/unify:0.6.0": num
#let resolve-default(a, b) = {
if a == none {
b
} else {
a
}
}
#let resolve-array(x) = {
if is-array(x) {
x
} else if is-none(x) {
()
} else {
(x,)
}
}
#let resolve-pt(x) = {
if is-length(x) {
return x
}
if is-string(x) {
return eval(x)
}
return x * 1pt
}
#let resolve-content(x) = {
if is-content(x) {
return x
}
return text(str(x))
}
#let resolve-color(x) = {
if is-color(x) {
return x
}
let colors = (
"red": red,
"white": white,
"black": black,
"purple": purple,
"none": black,
"yellow": yellow,
"blue": blue,
"orange": orange,
"green": green,
)
return colors.at(x, default: black)
}
#let resolve-math-content(x) = {
if is-content(x) {
return x
}
if is-number(x) {
return num(x)
}
return text(str(x))
}
#let is-str-frac(x) = {
return test(x, "/")
}
#let resolve-sink-content(sink) = {
let args = sink.pos()
let arg = args.at(0)
if arg != none {
return resolve-math-content(arg)
}
}
#let resolve-stroke(x) = {
return if is-string(x) { dictionary(strokes).at(x) } else {x }
}
#let resolve-fill(x) = {
return if is-string(x) { dictionary(fills).at(x) } else {x }
}
#let resolve-align(x) = {
return if is-string(x) { dictionary(alignments).at(x) } else {x }
}
#let resolve-float(x) = {
return if type(x) == length {
let r = "\d+(?:\.\d+)?"
let m = repr(x).match(regex(r))
float(m)
} else {
x
}
}
|
|
https://github.com/crd2333/Astro_typst_notebook | https://raw.githubusercontent.com/crd2333/Astro_typst_notebook/main/src/docs/here/to2/2.typ | typst | ---
title: '我的第一篇博客文章'
pubDate: 2022-07-01
description: '这是我 Astro 博客的第一篇文章。'
author: 'Astro 学习者'
tags: ["astro", "learning in public"]
---
= Typst 笔记
== Typst Compose paper faster
Fuck typst |
|
https://github.com/voXrey/cours-informatique | https://raw.githubusercontent.com/voXrey/cours-informatique/main/typst/15-files-de-priorité.typ | typst | #import "@preview/codly:0.2.1": *
#show: codly-init.with()
#codly()
#import "@preview/diagraph:0.2.4": *
#set text(font: "Roboto Serif")
= Partie III - Structure de Données <partie-iii---structure-de-données>
= Chapitre 15 : Files de Priorités <chapitre-15-files-de-priorités>
== I - Tas Binaire <i---tas-binaire>
Soit X un ensemble ordonné
Définition : Un tas binaire est un arbre binaire presque complet ayant la propriété de tas.
#quote(
block: true,
)[
Presque complet : tous les étages sont pleins sauf éventuellement le dernier qui est alors "rempli de gauche à droite" (voir exemple).
Propriété de tas :
- Tas-max : un élément de l’arbre est plus grand que ses (deux) fils.
- Tas-min : un élément est plus petit que ses fils.
]
Voyons un exemple.
#raw-render(
```dot
digraph {
A -> B
A -> C
B -> D
B -> G
C -> E
C -> F
D -> J
D -> H
G -> I
}
```,
labels: (
A: "13",
B: "8",
C: "12",
D: "4",
E: "3",
F: "7",
G: "2",
H: "3",
I: "1",
J: "2"
)
)
Important : Dans le dernier étage "il n’y a pas de trou", si un nœud de l’étage h-1 n’a pas deux enfants, alors tous les nœuds à sa droite n’ont pas d’enfant.
#quote(block: true)[
Remarque : appellation tas-max car le max est à la racine
]
=== Implémentation des Tas Binaires <implémentation-des-tas-binaires>
==== Tableau <tableau>
Ceci est possible justement parce que l’arbre est presque complet. Si un noeud est stocké en case $i$ du tableau, alors son fils gauche se trouve en case $2 i + 1$ et son fils droit en $2 i + 2$.
On place la racine en case 0.
Sur l’exemple
#figure(align(center)[#table(
columns: 10,
align: (col, row) => (
center,
center,
center,
center,
center,
center,
center,
center,
center,
center,
).at(col),
inset: 6pt,
[0],
[1],
[2],
[3],
[4],
[5],
[6],
[7],
[8],
[9],
[13],
[8],
[12],
[4],
[2],
[3],
[7],
[2],
[3],
[1],
)])
#quote(block: true)[
Remarque : Cela correspond à un parcours en largeur.
]
Opérations
- Ajouter un élément au tas
- Supprimer la racine
===== 1. Ajout <ajout>
Pour simplifier on suppose avoir des tableaux dynamiques.
====== Algorithme auxiliaire <algorithme-auxiliaire>
On aura besoin d’une opération auxiliaire : `percolate_up`.
Spécification `percolate_up` :
- Précondition : l’arbre manipulé est presque un tas : il y a au plus un nœud qui pose problème ; il est plus grand que son père.
- Postcondition : l’arbre est un tas binaire qui contient les mêmes éléments qu’au départ.
```md
Algorithme percolate_up :
Tant que le noeud "pointé" pose problème
Echanger ce noeud avec son père
```
Correction : Lors d’un échange, le nœud qui prend la place de son père est plus grand que son frère gauche par transitivité. La preuve est assez évidente, la précondition est vérifiée : il y a au plus un problème dans l’arbre, entre l’élément remonté et son nouveau père.
Complexité : A chaque étape le nœud pointé remonte d’un étage, donc l’algorithme est en O\(h\(t)). Sauf qu’ici, soit n le nombre d’éléments) comme l’arbre est presque complet, on a : $2^(h lr((t))) - 1 < n lt.eq 2^(h lr((t)) + 1) - 1$
Donc $h lr((t))$ \~ $l o g lr((n))$
Autre façon de le voir
Si un nœud se trouve en case $i$ du tableau, son père est en case $frac(i - 1, 2)$ du tableau. Donc notre algorithme a pour variant la quantité $l o g_2 lr((i + 1))$ donc une complexité $O lr((l o g_2 lr((i + 1))))$.
====== Algorithme principal <algorithme-principal>
On ajoute un élément en dernière case du tableau (que l’ont étend si nécessaire) et on appelle `percolate_up` sur ce dernier nœud.
==== 2. Suppression de la racine <suppression-de-la-racine>
Algorithme
- On remplace a racine par l’élément le plus à droite dans le tableau
- On appelle `percolate_down`
Algorithme `percolate_down`
```markdown
Tant que le noeud pointé pose problème
On échange le noeud avec le plus grand de ses fils
```
Précondition / Invariant de boucle : L’arbre est un tas sauf éventuellement au niveau du nœud pointé.
Complexité : $O lr((h lr((t)))) = O lr((l o g lr((n))))$
== II - Tri Par Tas <ii---tri-par-tas>
Deux étapes
#block[
#set enum(numbering: "1)", start: 1)
+ On transforme le tableau initial en un tas
+ On extrait successivement le max et on le range à sa place
]
Exemple : $a = { 13 , 8 , 1 , 7 , 18 , 4 , 0 , 12 }$
+ Invariant de boucle : $a lr([0 : i + 1])$ est un tas
$i = 0$ : 13 8 1 7 18 4 0 12
$i = 1$ : 13 8 1 7 18 4 0 12
$i = 2$ : 13 8 1 …
$i = 3$ : 13 8 1 7 18 …
$i = 4$ : 18 13 1 7 8 4 0 12 (flèche de 8 à 13 puis à 18)
$i = 5$ : 18 13 4 7 8 1 0 12 (flèche de 1 à 4)
$i = 6$ : 18 13 4 7 8 1 0 12
$i = 7$ : 18 13 4 12 8 1 0 7 (flèche de 7 à 12 et de 12 à 13)
Pour $i = 0$ à $n - 1$ : `percolate_up(i)`
Complexité : Chaque `percolate(i)` est en $O lr((l o g lr((i)))) lt.eq O lr((l o g lr((n))))$ donc le total est en $O lr((n l o g lr((n))))$.
+ Extraction du max (on remplace 7 et 18) puis on effectue `percolate_down`
Invariant : $a lr([0 : i])$ est un tas binaire et $a lr([i : n])$ est trié et contient des éléments supérieurs à ceux de $a lr([0 : i])$.
Algorithme :
```markdown
Pour i = n à 1
Échanger a[0] et a[i-1]
taille du tas -= 1
percolate_down(0)
```
Complexité : $O lr((n l o g lr((n))))$
Conclusion : Complexité temporelle en $O lr((n l o g lr((n))))$ et spatiale en $O lr((1))$
== III - Files de Priorités <iii---files-de-priorités>
Définition : #strong[Structure abstraite] qui permet de stocker des éléments munis d’une priorité.
Opérations
- Créer une file de priorité vide
- Ajouter un élément et sa priorité dans la file
- Extraire l’élément de priorité dans la file
- Tester si la file est vide
- Déterminer le minimum de la liste
- Mettre à jour une priorité pour la remplacer par une priorité plus faible
=== 1. Implémentations naïves <implémentations-naïves>
#figure(
align(
center,
)[#table(
columns: 5,
align: (col, row) => (center, center, center, center, center,).at(col),
inset: 6pt,
[],
[Min],
[Extract Min],
[Update Prio],
[Add],
[Tableaux triés par priorité],
[$O lr((1))$],
[$O lr((1)) \*$],
[$O lr((n))$],
[$O lr((n))$],
[Liste chaînée non triée],
[$O lr((n))$],
[$O lr((n))$],
[$O lr((1))$],
[$O lr((1))$],
[ABR équilibré],
[$O lr((l o g lr((n))))$],
[$O lr((l o g lr((n))))$],
[$O lr((l o g lr((n))))$],
[$O lr((l o g lr((n))))$],
)],
)
#emph[On note ] l’utilisation d’un tableau dynamique\*
=== 2. Implémentation via les tas binaires <implémentation-via-les-tas-binaires>
Créer une file vide : on crée un tas vide
File vide : facile
Trouver le minimum : il faut utiliser un `tas-min` $O lr((1))$
Extraire le minimum : cela correspond à la suppression de la racine d’un tas binaire $O lr((l o g lr((n))))$
Ajout d’un élément : ajout dans un tas binaire $O lr((l o g lr((n))))$
Mise à jour d’une priorité
- On met à jour la priorité
- Si la nouvelle priorité est inférieure à l’ancienne on appelle `percolate_up` $O lr((l o g lr((n))))$
Sinon, on appelle `percolate_down` $O lr((l o g lr((n))))$
=== 3. Remarque importante sur l’implémentation <remarque-importante-sur-limplémentation>
Dans les tas binaires, les nœuds contiennent une valeur dans un ensemble X donné (c’est un `'a tas_binaire`).
Ici, les étiquettes des nœuds sont des couples `(élément, priorité)`, la priorité joue le rôle de clé et l’élément de donnée satellite.
La clé sert donc à structurer le tas, c’est elle qui est utilisée dans les fonctions de tas (insertion, suppression…) tandis que la donnée satellite n’est pas lue.
Cependant, pour la mise à jour d’une priorité, on souhaiterait avoir une fonction
```c
void update_priority (tas, elt, new_prio);
```
Solution naïve : on cherche l’élément dans le tas pour mettre à jour la seconde composante du couple puis on appelle `percolate` depuis le nœud $O lr((n))$.
Solution préférable : On représente une file de priorité par un couple
- tas binaire de couples
- dictionnaire dont les clés sont les éléments (la donnée satellite) et dont les valeurs sont les indices du tableau qui implémente le tas où se trouve la priorité de l’élément concerné.
Conséquence : à chaque modification du tableau dans les fonctions de tas binaire il faut mettre à jour le dictionnaire.
|
|
https://github.com/zllmma/electromagnetic_field_and_wave_notes | https://raw.githubusercontent.com/zllmma/electromagnetic_field_and_wave_notes/main/notes.typ | typst | #import "@preview/ilm:1.2.1": *
#set text(lang: "zh")
#show: ilm.with(
title: [电磁场与电磁波笔记],
author: "ZLL",
date: datetime(year: 2024, month: 08, day: 06),
paper-size: "a4",
)
#set text(
font: ("New Computer Modern", "Noto Serif CJK SC"),
size: 13pt,
)
#let bq = blockquote
= 矢量分析
#bq([
笔者注: 严格的来讲, 矢量符号应该都是粗体, 但为了方便, 本文中部分矢量符号没有加粗
])
== 矢量表达
=== 三维直角坐标系
此坐标系中任一矢量 $bold(A)$ 可表示为:
#bq($
bold(A) &= bold(e)_x A_x + bold(e)_y A_y + bold(e)_z A_z\
&= sum_(i) A_i bold(e)_i quad (i = 1, 2, 3 "表示" x, y, z)\
&= A_i bold(e)_i quad "(爱因斯坦求和约定)"
$)
单位矢量 $bold(e)_x, bold(e)_y, bold(e)_z$ 满足:
#bq([$
e_i dot e_j = delta_(i j)
$
$
e_i times e_j = epsilon_(i j k) e_k
$])
其中 $delta_(i j)$ 叫做克罗内克 $delta$ 函数
#bq($
delta_(i j) = cases(
1 &", " i = j,
0 &", " i != j
)
$)
$epsilon_(i j k)$ 为列维-奇维塔符号
#bq($
epsilon_(i j k) = cases(
+1 quad& ("当" i, j, k "是偶排列", "即" (1, 2, 3) "的循环排列"),
-1 &("当" i, j, k "是奇排列", "即" (1, 2, 3) "的反循环排列"),
0 &(当 i = j, 或 i = k, 或 j = k)
)
$)
例: $e_z times e_y = epsilon_(z y x) e_x + epsilon_(z y y) e_y + epsilon_(z y z) e_z = -e_x$
- 矢量点乘
#blockquote($
bold(A) dot bold(B) = (A_i e_i) dot (B_j e_j) = A_i B_j (e_i dot e_j) = A_i B_i delta_(i j) = A_i B_i
$)
- 矢量叉乘
#blockquote($
bold(A) times bold(B) = (A_i e_i) times (B_j e_j) = A_i B_j (e_i times e_j) = A_i B_j epsilon_(i j k) e_k
$)
例: 当 $k$ 为 $x$ 时, 上式为 $A_y B_z epsilon_(y z x) e_x + A_z B_y epsilon_(z y x) e_x = e_x (A_y B_z - A_z B_y)$, 此即为叉乘结果的 $x$ 分量
叉乘结果也可写为
#blockquote($
bold(A) times bold(B) = mat(delim: "|", e_x, e_y, e_z; A_x, A_y, A_z; B_x, B_y, B_z)
$)
一个列维-奇维塔符号的性质:
#blockquote($
epsilon_(i j k) epsilon_(m n k) = delta_(i m) delta_(j n) - delta_(i n) delta_(j m)
$)
由此可证明 $A dot (B times C) = C dot (A times B) = B dot (C times A)$, 过程如下
#bq([$
&underbrace(A, k) dot (underbrace(B, i) times underbrace(C, j))\
&= A_k e_k dot (e_m B_i C_j epsilon_(i j m))\
&= delta_(k m) epsilon_(i j m) A_k B_i C_j = epsilon_(i j k) A_k B_i C_j\
&= epsilon_(j k i) A_k B_i C_j quad (B dot (C times A))\
&= epsilon_(k i j) A_k B_i C_j quad (C dot (A times B))
$])
== $nabla$ 算符运算
$nabla$算符 读作 "nabla" 或 "del", 其既有矢量性, 也有微分性
#bq([
$
nabla &= bold(e)_x (diff) / (diff x) + bold(e)_y (diff) / (diff y) + bold(e)_z (diff) / (diff z)\
&= bold(e)_i diff_i
$
])
- 标量场的梯度
#bq([
$
nabla U(bold(r)) = e_i diff_i U(bold(r))
$
])
- 矢量场的散度
#bq([
$
gradient dot bold(A)(bold(r)) = e_i diff_i dot A_j e_j = delta_(i j) diff_i A_j = diff_i A_i
$
])
- 矢量场的旋度
#bq([
$
gradient times bold(A)(bold(r)) &= e_i diff_i times e_j A_j = epsilon_(i j k) e_k diff_i A_j\
&= mat(delim: "|", e_x, e_y, e_z; diff/diff_x, diff/diff_y, diff/diff_z; A_x, A_y, A_z)
$
])
几个典型性质:
#bq([1. 假设$f, g$都是标量, 则 $ gradient(f g) = g(gradient f) + f(gradient g) $])
#bq([
证明:
$
gradient(f g) &= e_i diff_i (f g) = e_i (g (diff_i f) + f (diff_i g)) = g(gradient f) + f(gradient g)
$])
#bq([2. 假设$bold(A)$是矢量, 则 $ gradient times (gradient times bold(A)) = gradient(gradient dot bold(A)) - gradient^2 bold(A) $])
#bq([
证明:
$
gradient times (gradient times A) &= gradient times (e_k epsilon_(m n k) diff_m A_n)\
&= (e_j diff_j) times (e_k epsilon_(m n k) diff_m A_n)\
&= e_i epsilon_(i j k) epsilon_(m n k) diff_j diff_m A_n\
&= e_i (delta_(i m) delta_(j n) - delta_(i n) delta_(j m)) diff_j diff_m A_n\
&= e_i diff_j diff_i A_j - e_i diff_j diff_j A_i\
&= e_i diff_i (diff_j A_j) - diff^2_j e_i A_i\
&= gradient(gradient dot bold(A)) - gradient^2 bold(A)
$])
#bq([
$
gradient times (gradient u) &= gradient times (e_i diff_i u)\
&= e_k epsilon_(j i k) diff_j diff_i u\
&= -e_k epsilon_(i j k) diff_i diff_j u\
&= -gradient times (diff_j e_j u)\
&= -gradient times (gradient u) = 0
$
])
#bq([
$
gradient times (bold(F) times bold(G)) &= (bold(F) dot gradient) bold(G) - bold(G) (gradient dot bold(F))
$
])
== 矢量分析意义
=== 微元
- 线元
$
bold(r) = x e_x + y e_y + z e_z = u_i e_i\
bold(r)'= (u_i + dif u_i) e_i\
$
#bq($
dif bold(r) &= bold(r)' - bold(r) \
&= e_x dif x + e_y dif y +e_z dif z = e_i dif u_i
$)
- 面元
+ 一定是一个平面
+ 有方向(法向方向)
#bq($
dif bold(S) &= e_x dif S_x + e_y dif S_y + e_z dif S_z\
dif S_x &= dif y dif z e_x\
dif S_y &= dif x dif z e_y\
dif S_z &= dif x dif y e_z\
$)
- 体积元
#bq($
dif V = dif x dif y dif z
$)
=== 标量函数 (场) 的方向导数及梯度
标量场 $T(x, y z)$
等值面 $T(x, y, z) = C$
方向导数:
#bq([
$
(diff T(M_0)) / (diff l)|_(e_l) = lim_(Delta l -> 0) (T(M) - T(M_0)) / (Delta l)
$
])
$
dif bold(l) = dif l e_l = e_i dif u_i\
=> e_l = e_i (dif u_i) / (dif l)
$
#bq([
$
(diff T) / (diff l) &= (diff T) / (diff x) (dif x) / (dif l)+(diff T) / (diff y) (dif y) / (dif l)+(diff T) / (diff z) (dif z) / (dif l)\
&= ((diff T) / (diff u_j) e_j) dot ((dif u_i) / (dif l) e_i)\
&= gradient T dot bold(e)_l
$
])
这说明:
+ 标量场沿任意方向的方向导数等于其梯度在该方向上的投影
+ 标量场的梯度是一个矢量, 方向是标量场变化最快的方向, 垂直于等值面
=== 矢量场的通量和散度
- 矢量线
矢量线上任一点的切线方向与矢量场的在该点的方向相同, 即 $dif bold(r) "平行" bold(F)$
#bq($
(dif x) / F_x = (dif y) / F_y = (dif z) / F_z
$)
- 通量
#bq([
$
Psi = integral_S bold(F) dot dif bold(S)
$
])
- 散度
#bq([$
"div" bold(F) = lim_(Delta V -> 0) (integral.cont_S bold(F) dot dif bold(S)) / (Delta V) = gradient dot bold(F)
$])
- 散度定理
将散度的定义式稍作变换即得散度定理: *矢量场的散度在体积上的积分等于矢量场在该体积的闭合面上的面积分*
#bq([
$
integral_V gradient dot F dif V = integral.cont_S F dot dif S
$
])
=== 矢量场的环流与旋度
- 环流
矢量场沿一条*闭合*路径的线积分
#bq([
$
Gamma = integral.cont_C bold(F) dot dif bold(l)
$
])
- 环流面密度
#bq([
$
"rot"_upright(n) bold(F) = lim_(Delta S->0) (integral.cont_C bold(F) dot dif bold(l)) / (Delta S)
$
])
- 旋度
取不同的面元 $Delta S$, 环流面密度的值不同, 但是在某个特定方向下, 环流密度有最大值, 为解决这个问题, 引入旋度的概念
旋度定义为一个矢量, 方向是使环流密度取得最大值的面元法线方向, 大小为该最大环流密度的值
#bq([
$
"rot" bold(F) = bold(n) lim_(Delta S->0) lr((integral.cont_C bold(F) dot dif bold(l))/(Delta S)|)_max = gradient times bold(F)
$
])
- 斯托克斯定理
*矢量场的旋度在曲面上的积分等于矢量场在限定曲面的闭合曲线上的线积分*
#bq([
$
integral_S gradient times bold(F) dot dif bold(S) = integral.cont_C bold(F) dot dif bold(l)
$
])
== 无旋场与无散场
=== 无旋场
若一个矢量场的旋度处处为0, 即
#bq([
$
gradient times F eq.triple 0
$
])
则称其为无旋场, 是由散度源产生的 (如静电场)
由斯托克斯定理, 无旋场的曲线积分与路径无关, 只与起点和终点有关
- 一个结论: 标量场的梯度的旋度恒等于0
#bq([
$
gradient times (gradient u) eq.triple 0
$
])
由此得到: 一个无旋场总可以表示成某个标量场的梯度.
=== 无散场
类似的, 无散场满足任一点散度为0
#bq([
$
gradient dot F eq.triple 0
$
])
它是由漩涡源产生的 (如静磁场)
由高斯定理, 无散场通过任何闭合曲面的通量恒等于0
- 一个结论: 矢量场的旋度的散度等于0
#bq([
$
gradient dot (gradient times A) eq.triple 0
$
])
由此得到: 无散场总可以表示为一个矢量场的旋度
== 拉普拉斯运算与格林定理
=== 拉普拉斯运算
对标量的梯度再求散度, 称为对标量的拉普拉斯运算, 记作
#bq([
$
gradient dot (gradient u) &= gradient^2 u \
&= (diff^2 u) / (diff x^2) + (diff^2 u) / (diff y^2) + (diff^2 u) / (diff z^2) \
&= diff^2_i u
$
])
对矢量场的拉普拉斯运算定义为
#bq([
$
gradient^2 F &= gradient (gradient dot F) - gradient times (gradient times F)\
&= e_x gradient^2 F_x + e_y gradient^2 F_y + e_z gradient^2 F_z\
&= e_i gradient^2 F_i = e_i (diff^2_j F_i)
$
])
=== 格林定理
格林第二恒等式: $psi$, $phi$ 是两个任意标量函数, 则
#bq([
$
integral_(V) (phi gradient^2 psi - psi gradient^2 phi) dif V = integral.cont_S (
phi (diff psi) / (diff n) - psi (diff phi) / (diff n)
) dif S
$
])
== 亥姆霍兹定理
在有限的区域中, 任一矢量场由它的散度, 旋度和边界条件唯一地确定, 且可表示为一个无散场和一个无旋场的叠加 |
|
https://github.com/RodolpheThienard/typst-template | https://raw.githubusercontent.com/RodolpheThienard/typst-template/main/reports/2/template2.typ | typst | MIT License | #let project(title: none, authors: none, subtitle: none, img:none, body) = {
set text(font: "IBM Plex Mono", lang: "en")
set par(justify: true)
set page(
header: grid(columns: (1fr),
align(right + horizon)[#text(gray)[#title]],
),
footer: [
#line(length: 100%)
#grid(columns: (50%,50%),
align(left)[#text(gray)[#datetime.today().display("[Month repr:long] [day], [year]")]],
align(right, counter(page).display("1/1", both: true)))
]
)
let number-until-with(max-level, schema) = (..numbers) => {
if numbers.pos().len() <= max-level {
numbering(schema, ..numbers)
}
}
set heading(numbering: number-until-with(1, "I.a"))
show raw.where(block: true): it => {
set text(font: "IBM Plex Mono", size: 8pt)
set align(left)
set block(fill: luma(240), inset: 10pt, radius: 4pt, width: 100%,stroke: rgb("#000").lighten(80%),)
it
}
show raw.where(block: false): box.with(
fill: luma(240),
inset: (x: 3pt, y: 0pt),
outset: (y: 3pt),
radius: 2pt
)
show raw.where(block: false): text.with(font: "IBM Plex Mono")
// TITLE
grid(columns: (30%, 70%), column-gutter: 10pt,
align(left + horizon, image(img)),
align(left + horizon)[#text(18pt, fill: rgb("#007ba4"), [*#title*])\
#text(14pt, fill: maroon)[#subtitle]\
#grid(
columns: (1fr,) * 2,
row-gutter: 24pt,
..authors.map(author => [
#author.name \
#author.affiliation \
#if author.email != none [
#link("mailto:" + author.email)]
]),)],)
line(length: 100%)
columns(1,body)
}
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/repr-02.typ | typst | Other | // Colors and strokes.
#set text(0.8em)
#rgb("f7a205") \
#(2pt + rgb("f7a205"))
// Strings and escaping.
#raw(repr("hi"), lang: "typc")
#repr("a\n[]\"\u{1F680}string")
// Content.
#raw(lang: "typc", repr[*Hey*])
// Functions are invisible.
Nothing
#let f(x) = x
#f
#rect
#(() => none)
|
https://github.com/altaris/typst-symbols-a4 | https://raw.githubusercontent.com/altaris/typst-symbols-a4/master/typst-symbols-a4.typ | typst | MIT License | #set table(stroke: 0.1pt)
#let t2l(typst, latex, latexpkg: "") = {
(
[#eval(typst, mode: "math")],
[#text(typst, font: "Fira Code")],
[#text([\\#latex], font: "Fira Code")],
[#text(latexpkg, font: "Fira Code")],
)
}
#table(
columns: 4,
table.header([Symbol], [Typst], [LaTeX], [LaTeX pkg]),
..t2l("paren.l", "lparen"),
..t2l("paren.r", "rparen"),
..t2l("paren.t", "overparen"),
..t2l("paren.b", "underparen"),
..t2l("brace.l", "lbrace"),
..t2l("brace.r", "rbrace"),
..t2l("brace.t", "overbrace"),
..t2l("brace.b", "underbrace"),
..t2l("bracket.l", "lbrack"),
..t2l("bracket.l.double", "lBrack"),
..t2l("bracket.r", "rbrack"),
..t2l("bracket.r.double", "rBrack"),
..t2l("bracket.t", "overbracket"),
..t2l("bracket.b", "underbracket"),
..t2l("turtle.l", ""),
..t2l("turtle.r", ""),
..t2l("turtle.t", "obrbrak"),
..t2l("turtle.b", "ubrbrak"),
..t2l("bar.v", "vert"),
..t2l("bar.v.double", "Vert"),
..t2l("bar.v.triple", "Vvert"),
..t2l("bar.v.broken", "textbrokenbar", latexpkg: "textcomp"),
..t2l("bar.v.circle", "circledvert"),
..t2l("bar.h", "horizbar"),
..t2l("fence.l", "lvzigzag"),
..t2l("fence.l.double", "Lvzigzag"),
..t2l("fence.r", "rvzigzag"),
..t2l("fence.r.double", "Rvzigzag"),
..t2l("fence.dotted", "fourvdots"),
..t2l("angle", "angle"),
..t2l("angle.l", "langle"),
..t2l("angle.r", "rangle"),
..t2l("angle.l.double", "llangle", latexpkg: "MnSymnol"),
..t2l("angle.r.double", "rrangle", latexpkg: "MnSymnol"),
..t2l("angle.acute", "angdnr"),
..t2l("angle.arc", "measuredangle"),
..t2l("angle.arc.rev", "measuredangleleft"),
..t2l("angle.rev", "revangle"),
..t2l("angle.right", "rightangle"),
..t2l("angle.right.rev", ""),
..t2l("angle.right.arc", "measuredrightangle"),
..t2l("angle.right.dot", "rightanglemdot"),
..t2l("angle.right.sq", "rightanglesqr"),
..t2l("angle.spatial", "threedangle"),
..t2l("angle.spheric", "sphericalangle"),
..t2l("angle.spheric.rev", "gtlpar"),
..t2l("angle.spheric.top", "sphericalangleup"),
..t2l("amp", "mathampersand"),
..t2l("amp.inv", "upand"),
..t2l("ast.op", "ast"),
..t2l("ast.basic", ""),
..t2l("ast.low", ""),
..t2l("ast.double", ""),
..t2l("ast.triple", ""),
..t2l("ast.small", ""),
..t2l("ast.circle", "circledast"),
..t2l("ast.square", "boxast"),
..t2l("at", "mathatsign"),
..t2l("backslash", "backslash"),
..t2l("backslash.circle", "obslash"),
..t2l("backslash.not", "rsolbar"),
..t2l("co", ""),
..t2l("colon", "mathcolon"),
..t2l("colon.double", "Colon"),
..t2l("colon.eq", "coloneq"),
..t2l("colon.double.eq", "Coloneq"),
..t2l("comma", "mathcomma"),
..t2l("dagger", "dagger"),
..t2l("dagger.double", "ddagger"),
..t2l("dash.en", ""),
..t2l("dash.em", ""),
..t2l("dash.fig", ""),
..t2l("dash.wave", ""),
..t2l("dash.colon", "dashcolon"),
..t2l("dash.circle", "circleddash"),
..t2l("dash.wave.double", "hzigzag"),
..t2l("dot.op", "cdot"),
..t2l("dot.basic", "mathperiod"),
..t2l("dot.c", "cdotp"),
..t2l("dot.circle", "odot"),
..t2l("dot.circle.big", "bigodot"),
..t2l("dot.square", "boxdot"),
..t2l("dot.double", ""),
..t2l("dot.triple", "dddot"),
..t2l("dot.quad", "ddddot"),
..t2l("excl", "mathexclam"),
..t2l("excl.double", "Exclam"),
..t2l("excl.inv", ""),
..t2l("excl.quest", ""),
..t2l("quest", "mathquestion"),
..t2l("quest.double", "Question"),
..t2l("quest.excl", ""),
..t2l("quest.inv", ""),
..t2l("interrobang", ""),
..t2l("hash", "mathoctothorpe"),
..t2l("hyph", "mathhyphen"),
..t2l("hyph.minus", ""),
..t2l("hyph.nobreak", ""),
..t2l("hyph.point", ""),
..t2l("hyph.soft", ""),
..t2l("percent", "mathpercent"),
..t2l("copyright", "copyright"),
..t2l("copyright.sound", ""),
..t2l("permille", "permil", latexpkg: "wasysym"),
..t2l("pilcrow", "mathparagraph"),
..t2l("pilcrow.rev", ""),
..t2l("section", "mathsection"),
..t2l("semi", "mathsemicolon"),
..t2l("semi.rev", ""),
..t2l("slash", "mathslash"),
..t2l("slash.double", "sslash"),
..t2l("slash.triple", "trslash"),
..t2l("slash.big", "xsol"),
..t2l("dots.h.c", "unicodecdots"),
..t2l("dots.h", "unicodeellipsis"),
..t2l("dots.v", "vdots"),
..t2l("dots.down", "ddots"),
..t2l("dots.up", "adots"),
..t2l("tilde.op", "sim"),
..t2l("tilde.basic", ""),
..t2l("tilde.dot", "dotsim"),
..t2l("tilde.eq", "sime"),
..t2l("tilde.eq.not", "nsimeq"),
..t2l("tilde.eq.rev", "backsimeq"),
..t2l("tilde.equiv", "cong"),
..t2l("tilde.equiv.not", "ncong"),
..t2l("tilde.nequiv", "simneqq"),
..t2l("tilde.not", "nsim"),
..t2l("tilde.rev", "backsim"),
..t2l("tilde.rev.equiv", "backcong"),
..t2l("tilde.triple", "approxident"),
..t2l("acute", "textasciiacute", latexpkg: "textcomp"),
..t2l("acute.double", "textacutedbl", latexpkg: "textcomp"),
..t2l("breve", "textasciibreve", latexpkg: "textcomp"),
..t2l("caret", "caretinsert"),
..t2l("caron", "textasciicaron", latexpkg: "textcomp"),
..t2l("hat", ""),
..t2l("diaer", "textasciidieresis", latexpkg: "textcomp"),
..t2l("grave", "textasciigrave", latexpkg: "textcomp"),
..t2l("macron", "textasciimacron", latexpkg: "textcomp"),
..t2l("quote.double", "textquotedbl"),
..t2l("quote.single", "textquotesingle", latexpkg: "textcomp"),
..t2l("quote.l.double", "textquotedblleft"),
..t2l("quote.l.single", "textquoteleft"),
..t2l("quote.r.double", "textquotedblright"),
..t2l("quote.r.single", "textquoteright"),
..t2l("quote.angle.l.double", "guillemetleft"),
..t2l("quote.angle.l.single", "guilsinglleft"),
..t2l("quote.angle.r.double", "guillemetright"),
..t2l("quote.angle.r.single", "guilsinglright"),
..t2l("quote.high.double", ""),
..t2l("quote.high.single", ""),
..t2l("quote.low.double", "quotedblbase"),
..t2l("quote.low.single", "quotesinglbase"),
..t2l("prime", "prime"),
..t2l("prime.rev", "backprime"),
..t2l("prime.double", "dprime"),
..t2l("prime.double.rev", "backdprime"),
..t2l("prime.triple", "trprime"),
..t2l("prime.triple.rev", "backtrprime"),
..t2l("prime.quad", "qprime"),
..t2l("plus", "mathplus"),
..t2l("plus.circle", "oplus"),
..t2l("plus.circle.arrow", "rightarrowonoplus"),
..t2l("plus.circle.big", "bigoplus"),
..t2l("plus.dot", "dotplus"),
..t2l("plus.minus", "pm"),
..t2l("plus.small", ""),
..t2l("plus.square", "boxplus"),
..t2l("plus.triangle", "triangleplus"),
..t2l("minus", "minus"),
..t2l("minus.circle", "ominus"),
..t2l("minus.dot", "dotminus"),
..t2l("minus.plus", "mp"),
..t2l("minus.square", "boxminus"),
..t2l("minus.tilde", "eqsim"),
..t2l("minus.triangle", "triangleminus"),
..t2l("div", "div"),
..t2l("div.circle", "odiv"),
..t2l("times", "times"),
..t2l("times.big", "bigtimes"),
..t2l("times.circle", "otimes"),
..t2l("times.circle.big", "bigotimes"),
..t2l("times.div", "divideontimes"),
..t2l("times.three.l", "leftthreetimes"),
..t2l("times.three.r", "rightthreetimes"),
..t2l("times.l", "ltimes"),
..t2l("times.r", "rtimes"),
..t2l("times.square", "boxtimes"),
..t2l("times.triangle", "triangletimes"),
..t2l("ratio", "mathratio"),
..t2l("eq", "equal"),
..t2l("eq.star", "stareq"),
..t2l("eq.circle", "circledequal"),
..t2l("eq.colon", "eqcolon"),
..t2l("eq.def", "eqdef"),
..t2l("eq.delta", "triangleq"),
..t2l("eq.equi", "veeeq"),
..t2l("eq.est", "wedgeq"),
..t2l("eq.gt", "eqgtr"),
..t2l("eq.lt", "eqless"),
..t2l("eq.m", "measeq"),
..t2l("eq.not", "ne"),
..t2l("eq.prec", "curlyeqprec"),
..t2l("eq.quest", "questeq"),
..t2l("eq.small", ""),
..t2l("eq.succ", "curlyeqsucc"),
..t2l("eq.triple", "equiv"),
..t2l("eq.quad", "Equiv"),
..t2l("gt", "greater"),
..t2l("gt.circle", "ogreaterthan"),
..t2l("gt.curly", "succ"),
..t2l("gt.curly.approx", "succapprox"),
..t2l("gt.curly.double", "Succ"),
..t2l("gt.curly.eq", "succcurlyeq"),
..t2l("gt.curly.eq.not", "nsucccurlyeq"),
..t2l("gt.curly.equiv", "succeqq"),
..t2l("gt.curly.napprox", "succnapprox"),
..t2l("gt.curly.nequiv", "succneqq"),
..t2l("gt.curly.not", "nsucc"),
..t2l("gt.curly.ntilde", "succnsim"),
..t2l("gt.curly.tilde", "succsim"),
..t2l("gt.dot", "gtrdot"),
..t2l("gt.approx", "gtrapprox"),
..t2l("gt.double", "gg"),
..t2l("gt.eq", "geq"),
..t2l("gt.eq.slant", "geqslant"),
..t2l("gt.eq.lt", "gtreqless"),
..t2l("gt.eq.not", "ngeq"),
..t2l("gt.equiv", "geqq"),
..t2l("gt.lt", "gtrless"),
..t2l("gt.lt.not", "ngtrless"),
..t2l("gt.napprox", "gnapprox"),
..t2l("gt.nequiv", "gneqq"),
..t2l("gt.not", "ngtr"),
..t2l("gt.ntilde", "gnsim"),
..t2l("gt.small", ""),
..t2l("gt.tilde", "gtrsim"),
..t2l("gt.tilde.not", "ngtrsim"),
..t2l("gt.tri", "vartriangleright"),
..t2l("gt.tri.eq", "trianglerighteq"),
..t2l("gt.tri.eq.not", "ntrianglerighteq"),
..t2l("gt.tri.not", "nvartriangleright"),
..t2l("gt.triple", "ggg"),
..t2l("gt.triple.nested", "gggnest"),
..t2l("lt", "less"),
..t2l("lt.circle", "olessthan"),
..t2l("lt.curly", "prec"),
..t2l("lt.curly.approx", "precapprox"),
..t2l("lt.curly.double", "Prec"),
..t2l("lt.curly.eq", "preccurlyeq"),
..t2l("lt.curly.eq.not", "npreccurlyeq"),
..t2l("lt.curly.equiv", "preceqq"),
..t2l("lt.curly.napprox", "precnapprox"),
..t2l("lt.curly.nequiv", "precneqq"),
..t2l("lt.curly.not", "nprec"),
..t2l("lt.curly.ntilde", "precnsim"),
..t2l("lt.curly.tilde", "precsim"),
..t2l("lt.dot", "lessdot"),
..t2l("lt.approx", "lessapprox"),
..t2l("lt.double", "ll"),
..t2l("lt.eq", "leq"),
..t2l("lt.eq.slant", "leqslant"),
..t2l("lt.eq.gt", "lesseqgtr"),
..t2l("lt.eq.not", "nleq"),
..t2l("lt.equiv", "leqq"),
..t2l("lt.gt", "lessgtr"),
..t2l("lt.gt.not", "nlessgtr"),
..t2l("lt.napprox", "lnapprox"),
..t2l("lt.nequiv", "lneqq"),
..t2l("lt.not", "nless"),
..t2l("lt.ntilde", "lnsim"),
..t2l("lt.small", ""),
..t2l("lt.tilde", "lesssim"),
..t2l("lt.tilde.not", "nlesssim"),
..t2l("lt.tri", "vartriangleleft"),
..t2l("lt.tri.eq", "trianglelefteq"),
..t2l("lt.tri.eq.not", "ntrianglelefteq"),
..t2l("lt.tri.not", "nvartriangleleft"),
..t2l("lt.triple", "lll"),
..t2l("lt.triple.nested", "lllnest"),
..t2l("approx", "approx"),
..t2l("approx.eq", "approxeq"),
..t2l("approx.not", "napprox"),
..t2l("prec", "prec"),
..t2l("prec.approx", "precapprox"),
..t2l("prec.double", "Prec"),
..t2l("prec.eq", "preccurlyeq"),
..t2l("prec.eq.not", "npreccurlyeq"),
..t2l("prec.equiv", "preceqq"),
..t2l("prec.napprox", "precnapprox"),
..t2l("prec.nequiv", "precneqq"),
..t2l("prec.not", "nprec"),
..t2l("prec.ntilde", "precnsim"),
..t2l("prec.tilde", "precsim"),
..t2l("succ", "succ"),
..t2l("succ.approx", "succapprox"),
..t2l("succ.double", "Succ"),
..t2l("succ.eq", "succcurlyeq"),
..t2l("succ.eq.not", "nsucccurlyeq"),
..t2l("succ.equiv", "succeqq"),
..t2l("succ.napprox", "succnapprox"),
..t2l("succ.nequiv", "succneqq"),
..t2l("succ.not", "nsucc"),
..t2l("succ.ntilde", "succnsim"),
..t2l("succ.tilde", "succsim"),
..t2l("equiv", "equiv"),
..t2l("equiv.not", "nequiv"),
..t2l("prop", "propto"),
..t2l("emptyset", "varnothing"),
..t2l("emptyset.rev", "revemptyset"),
..t2l("nothing", "varnothing"),
..t2l("nothing.rev", "revemptyset"),
..t2l("without", "setminus"),
..t2l("complement", "complement"),
..t2l("in", "in"),
..t2l("in.not", "notin"),
..t2l("in.rev", "ni"),
..t2l("in.rev.not", "nni"),
..t2l("in.rev.small", "smallni"),
..t2l("in.small", "smallin"),
..t2l("subset", "subset"),
..t2l("subset.dot", "subsetdot"),
..t2l("subset.double", "Subset"),
..t2l("subset.eq", "subseteq"),
..t2l("subset.eq.not", "nsubseteq"),
..t2l("subset.eq.sq", "sqsubseteq"),
..t2l("subset.eq.sq.not", "nsqsubseteq"),
..t2l("subset.neq", "subsetneq"),
..t2l("subset.not", "nsubset"),
..t2l("subset.sq", "sqsubset"),
..t2l("subset.sq.neq", "sqsubsetneq"),
..t2l("supset", "supset"),
..t2l("supset.dot", "supsetdot"),
..t2l("supset.double", "Supset"),
..t2l("supset.eq", "supseteq"),
..t2l("supset.eq.not", "nsupseteq"),
..t2l("supset.eq.sq", "sqsupseteq"),
..t2l("supset.eq.sq.not", "nsqsupseteq"),
..t2l("supset.neq", "supsetneq"),
..t2l("supset.not", "nsupset"),
..t2l("supset.sq", "sqsupset"),
..t2l("supset.sq.neq", "sqsupsetneq"),
..t2l("union", "cup"),
..t2l("union.arrow", "cupleftarrow"),
..t2l("union.big", "bigcup"),
..t2l("union.dot", "cupdot"),
..t2l("union.dot.big", "bigcupdot"),
..t2l("union.double", "Cup"),
..t2l("union.minus", "uminus"),
..t2l("union.or", "cupvee"),
..t2l("union.plus", "uplus"),
..t2l("union.plus.big", "biguplus"),
..t2l("union.sq", "sqcup"),
..t2l("union.sq.big", "bigsqcup"),
..t2l("union.sq.double", "Sqcup"),
..t2l("sect", "cap"),
..t2l("sect.and", "capwedge"),
..t2l("sect.big", "bigcap"),
..t2l("sect.dot", "capdot"),
..t2l("sect.double", "Cap"),
..t2l("sect.sq", "sqcap"),
..t2l("sect.sq.big", "bigsqcap"),
..t2l("sect.sq.double", "Sqcap"),
..t2l("infinity", "infty"),
..t2l("oo", "infty"),
..t2l("diff", "partial"),
..t2l("partial", "partial"),
..t2l("gradient", "nabla"),
..t2l("nabla", "nabla"),
..t2l("sum", "sum"),
..t2l("sum.integral", "sumint"),
..t2l("product", "prod"),
..t2l("product.co", "coprod"),
..t2l("integral", "int"),
..t2l("integral.arrow.hook", "intlarhk"),
..t2l("integral.ccw", "awint"),
..t2l("integral.cont", "oint"),
..t2l("integral.cont.ccw", "ointctrclockwise"),
..t2l("integral.cont.cw", "varointclockwise"),
..t2l("integral.cw", "intclockwise"),
..t2l("integral.dash", "intbar"),
..t2l("integral.dash.double", "intBar"),
..t2l("integral.double", "iint"),
..t2l("integral.quad", "iiiint"),
..t2l("integral.sect", "intcap"),
..t2l("integral.slash", "fint"),
..t2l("integral.square", "sqint"),
..t2l("integral.surf", "oiint"),
..t2l("integral.times", "intx"),
..t2l("integral.triple", "iiint"),
..t2l("integral.union", "intcup"),
..t2l("integral.vol", "oiiint"),
..t2l("laplace", "increment"),
..t2l("forall", "forall"),
..t2l("exists", "exists"),
..t2l("exists.not", "nexists"),
..t2l("top", "top"),
..t2l("bot", "bot"),
..t2l("not", "neg"),
..t2l("and", "wedge"),
..t2l("and.big", "bigwedge"),
..t2l("and.curly", "curlywedge"),
..t2l("and.dot", "wedgedot"),
..t2l("and.double", "Wedge"),
..t2l("or", "vee"),
..t2l("or.big", "bigvee"),
..t2l("or.curly", "curlyvee"),
..t2l("or.dot", "veedot"),
..t2l("or.double", "Vee"),
..t2l("xor", "oplus"),
..t2l("xor.big", "bigoplus"),
..t2l("models", "models"),
..t2l("forces", "Vdash"),
..t2l("forces.not", "nVdash"),
..t2l("therefore", "therefore"),
..t2l("because", "because"),
..t2l("qed", "QED"),
..t2l("compose", "vysmwhtcircle"),
..t2l("convolve", "ast"),
..t2l("multimap", "multimap"),
..t2l("divides", "mid"),
..t2l("divides.not", "nmid"),
..t2l("wreath", "wr"),
..t2l("parallel", "parallel"),
..t2l("parallel.circle", "circledparallel"),
..t2l("parallel.not", "nparallel"),
..t2l("perp", "perp"),
..t2l("perp.circle", "operp"),
..t2l("diameter", "diameter"),
..t2l("join", "Join"),
..t2l("join.r", "rightouterjoin"),
..t2l("join.l", "leftouterjoin"),
..t2l("join.l.r", "fullouterjoin"),
..t2l("degree", "degree", latexpkg: "gensymb"),
..t2l("degree.c", "celsius", latexpkg: "gensymb"),
..t2l("degree.f", ""),
..t2l("smash", "smashtimes"),
..t2l("bitcoin", "faBtc", latexpkg: "fontawesome"),
..t2l("dollar", "mathdollar"),
..t2l("euro", "euro"),
..t2l("franc", ""),
..t2l("lira", "textlira"),
..t2l("peso", "textpeso"),
..t2l("pound", "pounds"),
..t2l("ruble", "faRub", latexpkg: "fontawesome"),
..t2l("rupee", "rupee", latexpkg: "tfrupee"),
..t2l("won", "textwon"),
..t2l("yen", "textyen"),
..t2l("ballot", ""),
..t2l("ballot.x", ""),
..t2l("checkmark", "checkmark"),
..t2l("checkmark.light", ""),
..t2l("floral", ""),
..t2l("floral.l", ""),
..t2l("floral.r", ""),
..t2l("notes.up", ""),
..t2l("notes.down", ""),
..t2l("refmark", ""),
..t2l("servicemark", ""),
..t2l("maltese", "maltese"),
..t2l("suit.club", "clubsuit"),
..t2l("suit.diamond", "vardiamondsuit"),
..t2l("suit.heart", "varheartsuit"),
..t2l("suit.spade", "spadesuit"),
..t2l("bullet", "smblkcircle"),
..t2l("circle.stroked", "mdlgwhtcircle"),
..t2l("circle.stroked.tiny", "vysmwhtcircle"),
..t2l("circle.stroked.small", "mdsmwhtcircle"),
..t2l("circle.stroked.big", "lgwhtcircle"),
..t2l("circle.filled", "mdlgblkcircle"),
..t2l("circle.filled.tiny", "mdsmblkcircle"),
..t2l("circle.filled.small", "vysmblkcircle"),
..t2l("circle.filled.big", "lgblkcircle"),
..t2l("circle.dotted", "dottedcircle"),
..t2l("circle.nested", "circledcirc"),
..t2l("ellipse.stroked.h", "whthorzoval"),
..t2l("ellipse.stroked.v", "whtvertoval"),
..t2l("ellipse.filled.h", "blkhorzoval"),
..t2l("ellipse.filled.v", "blkvertoval"),
..t2l("triangle.stroked.r", "triangleright"),
..t2l("triangle.stroked.l", "triangleleft"),
..t2l("triangle.stroked.t", "bigtriangleup"),
..t2l("triangle.stroked.b", "bigtriangledown"),
..t2l("triangle.stroked.bl", "lltriangle"),
..t2l("triangle.stroked.br", "lrtriangle"),
..t2l("triangle.stroked.tl", "ultriangle"),
..t2l("triangle.stroked.tr", "urtriangle"),
..t2l("triangle.stroked.small.r", "smalltriangleright"),
..t2l("triangle.stroked.small.b", "triangledown"),
..t2l("triangle.stroked.small.l", "smalltriangleleft"),
..t2l("triangle.stroked.small.t", "vartriangle"),
..t2l("triangle.stroked.rounded", ""),
..t2l("triangle.stroked.nested", "whiteinwhitetriangle"),
..t2l("triangle.stroked.dot", "trianglecdot"),
..t2l("triangle.filled.r", "blacktriangleright"),
..t2l("triangle.filled.l", "blacktriangleleft"),
..t2l("triangle.filled.t", "bigblacktriangleup"),
..t2l("triangle.filled.b", "bigblacktriangledown"),
..t2l("triangle.filled.bl", "llblacktriangle"),
..t2l("triangle.filled.br", "lrblacktriangle"),
..t2l("triangle.filled.tl", "ulblacktriangle"),
..t2l("triangle.filled.tr", "urblacktriangle"),
..t2l("triangle.filled.small.r", "smallblacktriangleright"),
..t2l("triangle.filled.small.b", "blacktriangledown"),
..t2l("triangle.filled.small.l", "smallblacktriangleleft"),
..t2l("triangle.filled.small.t", "blacktriangle"),
..t2l("square.stroked", "mdlgwhtsquare"),
..t2l("square.stroked.tiny", "smwhtsquare"),
..t2l("square.stroked.small", "mdsmwhtsquare"),
..t2l("square.stroked.medium", "mdwhtsquare"),
..t2l("square.stroked.big", "lgwhtsquare"),
..t2l("square.stroked.dotted", "dottedsquare"),
..t2l("square.stroked.rounded", "squoval"),
..t2l("square.filled", "mdlgblksquare"),
..t2l("square.filled.tiny", "smblksquare"),
..t2l("square.filled.small", "mdsmblksquare"),
..t2l("square.filled.medium", "mdblksquare"),
..t2l("square.filled.big", "lgblksquare"),
..t2l("rect.stroked.h", "hrectangle"),
..t2l("rect.stroked.v", "vrectangle"),
..t2l("rect.filled.h", "hrectangleblack"),
..t2l("rect.filled.v", "vrectangleblack"),
..t2l("penta.stroked", "pentagon"),
..t2l("penta.filled", "pentagonblack"),
..t2l("hexa.stroked", "varhexagon"),
..t2l("hexa.filled", "varhexagonblack"),
..t2l("diamond.stroked", "mdlgwhtdiamond"),
..t2l("diamond.stroked.small", "smwhtdiamond"),
..t2l("diamond.stroked.medium", "mdwhtdiamond"),
..t2l("diamond.stroked.dot", "diamondcdot"),
..t2l("diamond.filled", "mdlgblkdiamond"),
..t2l("diamond.filled.medium", "mdblkdiamond"),
..t2l("diamond.filled.small", "smblkdiamond"),
..t2l("lozenge.stroked", "mdlgwhtlozenge"),
..t2l("lozenge.stroked.small", "smwhtlozenge"),
..t2l("lozenge.stroked.medium", "mdwhtlozenge"),
..t2l("lozenge.filled", "mdlgblklozenge"),
..t2l("lozenge.filled.small", "smblklozenge"),
..t2l("lozenge.filled.medium", "mdblklozenge"),
..t2l("star.op", "star"),
..t2l("star.stroked", "bigwhitestar"),
..t2l("star.filled", "bigstar"),
..t2l("arrow.r", "rightarrow"),
..t2l("arrow.r.long.bar", "longmapsto"),
..t2l("arrow.r.bar", "mapsto"),
..t2l("arrow.r.curve", "rightdowncurvedarrow"),
..t2l("arrow.r.dashed", "rightdasharrow"),
..t2l("arrow.r.dotted", "rightdotarrow"),
..t2l("arrow.r.double", "Rightarrow"),
..t2l("arrow.r.double.bar", "Mapsto"),
..t2l("arrow.r.double.long", "Longrightarrow"),
..t2l("arrow.r.double.long.bar", "Longmapsto"),
..t2l("arrow.r.double.not", "nRightarrow"),
..t2l("arrow.r.filled", "rightblackarrow", latexpkg: "boisik"),
..t2l("arrow.r.hook", "hookrightarrow"),
..t2l("arrow.r.long", "longrightarrow"),
..t2l("arrow.r.long.squiggly", "longrightsquigarrow"),
..t2l("arrow.r.loop", "looparrowright"),
..t2l("arrow.r.not", "nrightarrow"),
..t2l("arrow.r.quad", "RRightarrow"),
..t2l("arrow.r.squiggly", "rightsquigarrow"),
..t2l("arrow.r.stop", "rightarrowbar"),
..t2l("arrow.r.stroked", "rightwhitearrow"),
..t2l("arrow.r.tail", "rightarrowtail"),
..t2l("arrow.r.tilde", "similarrightarrow"),
..t2l("arrow.r.triple", "Rrightarrow"),
..t2l("arrow.r.twohead.bar", "twoheadmapsto"),
..t2l("arrow.r.twohead", "twoheadrightarrow"),
..t2l("arrow.r.wave", "rightwavearrow"),
..t2l("arrow.l", "leftarrow"),
..t2l("arrow.l.bar", "mapsfrom"),
..t2l("arrow.l.curve", "leftdowncurvedarrow"),
..t2l("arrow.l.dashed", "leftdasharrow"),
..t2l("arrow.l.dotted", "leftdotarrow"),
..t2l("arrow.l.double", "Leftarrow"),
..t2l("arrow.l.double.bar", "Mapsfrom"),
..t2l("arrow.l.double.long", "Longleftarrow"),
..t2l("arrow.l.double.long.bar", "Longmapsfrom"),
..t2l("arrow.l.double.not", "nLeftarrow"),
..t2l("arrow.l.filled", "leftblackarrow", latexpkg: "boisik"),
..t2l("arrow.l.hook", "hookleftarrow"),
..t2l("arrow.l.long", "longleftarrow"),
..t2l("arrow.l.long.bar", "longmapsfrom"),
..t2l("arrow.l.long.squiggly", "longleftsquigarrow"),
..t2l("arrow.l.loop", "looparrowleft"),
..t2l("arrow.l.not", "nleftarrow"),
..t2l("arrow.l.quad", "LLeftarrow"),
..t2l("arrow.l.squiggly", "leftsquigarrow"),
..t2l("arrow.l.stop", "barleftarrow"),
..t2l("arrow.l.stroked", "leftwhitearrow"),
..t2l("arrow.l.tail", "leftarrowtail"),
..t2l("arrow.l.tilde", "similarleftarrow"),
..t2l("arrow.l.triple", "Lleftarrow"),
..t2l("arrow.l.twohead.bar", "twoheadmapsfrom"),
..t2l("arrow.l.twohead", "twoheadleftarrow"),
..t2l("arrow.l.wave", "leftwavearrow"),
..t2l("arrow.t", "uparrow"),
..t2l("arrow.t.bar", "mapsup"),
..t2l("arrow.t.curve", "uprightcurvearrow"),
..t2l("arrow.t.dashed", "updasharrow"),
..t2l("arrow.t.double", "Uparrow"),
..t2l("arrow.t.filled", "upblackarrow", latexpkg: "boisik"),
..t2l("arrow.t.quad", "UUparrow"),
..t2l("arrow.t.stop", "baruparrow"),
..t2l("arrow.t.stroked", "upwhitearrow"),
..t2l("arrow.t.triple", "Uuparrow"),
..t2l("arrow.t.twohead", "twoheaduparrow"),
..t2l("arrow.b", "downarrow"),
..t2l("arrow.b.bar", "mapsdown"),
..t2l("arrow.b.curve", "downrightcurvedarrow"),
..t2l("arrow.b.dashed", "downdasharrow"),
..t2l("arrow.b.double", "Downarrow"),
..t2l("arrow.b.filled", "downblackarrow", latexpkg: "boisik"),
..t2l("arrow.b.quad", "DDownarrow"),
..t2l("arrow.b.stop", "downarrowbar"),
..t2l("arrow.b.stroked", "downwhitearrow"),
..t2l("arrow.b.triple", "Ddownarrow"),
..t2l("arrow.b.twohead", "twoheaddownarrow"),
..t2l("arrow.l.r", "leftrightarrow"),
..t2l("arrow.l.r.double", "Leftrightarrow"),
..t2l("arrow.l.r.double.long", "Longleftrightarrow"),
..t2l("arrow.l.r.double.not", "nLeftrightarrow"),
..t2l("arrow.l.r.filled", "leftrightblackarrow", latexpkg: "boisik"),
..t2l("arrow.l.r.long", "longleftrightarrow"),
..t2l("arrow.l.r.not", "nleftrightarrow"),
..t2l("arrow.l.r.stroked", ""),
..t2l("arrow.l.r.wave", "leftrightsquigarrow"),
..t2l("arrow.t.b", "updownarrow"),
..t2l("arrow.t.b.double", "Updownarrow"),
..t2l("arrow.t.b.filled", "updownblackarrow", latexpkg: "boisik"),
..t2l("arrow.t.b.stroked", ""),
..t2l("arrow.tr", "nearrow"),
..t2l("arrow.tr.double", "Nearrow"),
..t2l("arrow.tr.filled", ""),
..t2l("arrow.tr.hook", "hknearrow"),
..t2l("arrow.tr.stroked", ""),
..t2l("arrow.br", "searrow"),
..t2l("arrow.br.double", "Searrow"),
..t2l("arrow.br.filled", ""),
..t2l("arrow.br.hook", "hksearrow"),
..t2l("arrow.br.stroked", ""),
..t2l("arrow.tl", "nwarrow"),
..t2l("arrow.tl.double", "Nwarrow"),
..t2l("arrow.tl.filled", ""),
..t2l("arrow.tl.hook", "hknwarrow"),
..t2l("arrow.tl.stroked", ""),
..t2l("arrow.bl", "swarrow"),
..t2l("arrow.bl.double", "Swarrow"),
..t2l("arrow.bl.filled", ""),
..t2l("arrow.bl.hook", "hkswarrow"),
..t2l("arrow.bl.stroked", ""),
..t2l("arrow.tl.br", "nwsearrow"),
..t2l("arrow.tr.bl", "neswarrow"),
..t2l("arrow.ccw", "acwopencirclearrow"),
..t2l("arrow.ccw.half", "curvearrowleft"),
..t2l("arrow.cw", "cwopencirclearrow"),
..t2l("arrow.cw.half", "curvearrowright"),
..t2l("arrow.zigzag", "downzigzagarrow"),
..t2l("arrows.rr", "rightrightarrows"),
..t2l("arrows.ll", "leftleftarrows"),
..t2l("arrows.tt", "upuparrows"),
..t2l("arrows.bb", "downdownarrows"),
..t2l("arrows.lr", "leftrightarrows"),
..t2l("arrows.lr.stop", "barleftarrowrightarrowbar"),
..t2l("arrows.rl", "rightleftarrows"),
..t2l("arrows.tb", "updownarrows"),
..t2l("arrows.bt", "downuparrows"),
..t2l("arrows.rrr", "rightthreearrows"),
..t2l("arrows.lll", "leftthreearrows"),
..t2l("arrowhead.t", ""),
..t2l("arrowhead.b", ""),
..t2l("harpoon.rt", "rightharpoonup"),
..t2l("harpoon.rt.bar", "barrightharpoonup"),
..t2l("harpoon.rt.stop", "rightharpoonupbar"),
..t2l("harpoon.rb", "rightharpoondown"),
..t2l("harpoon.rb.bar", "barrightharpoondown"),
..t2l("harpoon.rb.stop", "rightharpoondownbar"),
..t2l("harpoon.lt", "leftharpoonup"),
..t2l("harpoon.lt.bar", "leftharpoonupbar"),
..t2l("harpoon.lt.stop", "barleftharpoonup"),
..t2l("harpoon.lb", "leftharpoondown"),
..t2l("harpoon.lb.bar", "leftharpoondownbar"),
..t2l("harpoon.lb.stop", "barleftharpoondown"),
..t2l("harpoon.tl", "upharpoonleft"),
..t2l("harpoon.tl.bar", "upharpoonleftbar"),
..t2l("harpoon.tl.stop", "barupharpoonleft"),
..t2l("harpoon.tr", "upharpoonright"),
..t2l("harpoon.tr.bar", "upharpoonrightbar"),
..t2l("harpoon.tr.stop", "barupharpoonright"),
..t2l("harpoon.bl", "downharpoonleft"),
..t2l("harpoon.bl.bar", "bardownharpoonleft"),
..t2l("harpoon.bl.stop", "downharpoonleftbar"),
..t2l("harpoon.br", "downharpoonright"),
..t2l("harpoon.br.bar", "bardownharpoonright"),
..t2l("harpoon.br.stop", "downharpoonrightbar"),
..t2l("harpoon.lt.rt", "leftrightharpoonupup"),
..t2l("harpoon.lb.rb", "leftrightharpoondowndown"),
..t2l("harpoon.lb.rt", "leftrightharpoondownup"),
..t2l("harpoon.lt.rb", "leftrightharpoonupdown"),
..t2l("harpoon.tl.bl", "updownharpoonleftleft"),
..t2l("harpoon.tr.br", "updownharpoonrightright"),
..t2l("harpoon.tl.br", "updownharpoonleftright"),
..t2l("harpoon.tr.bl", "updownharpoonrightleft"),
..t2l("harpoons.rtrb", "rightharpoonsupdown"),
..t2l("harpoons.blbr", "downharpoonsleftright"),
..t2l("harpoons.bltr", "downupharpoonsleftright"),
..t2l("harpoons.lbrb", "leftrightharpoonsdown"),
..t2l("harpoons.ltlb", "leftharpoonsupdown"),
..t2l("harpoons.ltrb", "leftrightharpoons"),
..t2l("harpoons.ltrt", "leftrightharpoonsup"),
..t2l("harpoons.rblb", "rightleftharpoonsdown"),
..t2l("harpoons.rtlb", "rightleftharpoons"),
..t2l("harpoons.rtlt", "rightleftharpoonsup"),
..t2l("harpoons.tlbr", "updownharpoonsleftright"),
..t2l("harpoons.tltr", "upharpoonsleftright"),
..t2l("tack.r", "vdash"),
..t2l("tack.r.not", "nvdash"),
..t2l("tack.r.long", "vlongdash"),
..t2l("tack.r.short", "assert"),
..t2l("tack.r.double", "vDash"),
..t2l("tack.r.double.not", "nvDash"),
..t2l("tack.l", "dashv"),
..t2l("tack.l.long", "longdashv"),
..t2l("tack.l.short", "shortlefttack"),
..t2l("tack.l.double", "Dashv"),
..t2l("tack.t", "bot"),
..t2l("tack.t.big", "bigbot"),
..t2l("tack.t.double", "Vbar"),
..t2l("tack.t.short", "shortuptack"),
..t2l("tack.b", "top"),
..t2l("tack.b.big", "bigtop"),
..t2l("tack.b.double", "barV"),
..t2l("tack.b.short", "shortdowntack"),
..t2l("tack.l.r", "dashVdash"),
..t2l("alpha", "mupalpha"),
..t2l("beta", "mupbeta"),
..t2l("beta.alt", ""),
..t2l("chi", "mupchi"),
..t2l("delta", "mupdelta"),
..t2l("epsilon", "mupvarepsilon"),
..t2l("epsilon.alt", "mupepsilon"),
..t2l("eta", "mupeta"),
..t2l("gamma", "mupgamma"),
..t2l("iota", "mupiota"),
..t2l("kai", ""),
..t2l("kappa", "mupkappa"),
..t2l("kappa.alt", "mupvarkappa"),
..t2l("lambda", "muplambda"),
..t2l("mu", "mupmu"),
..t2l("nu", "mupnu"),
..t2l("ohm", "ohm", latexpkg: "gensymb"),
..t2l("ohm.inv", "mho"),
..t2l("omega", "mupomega"),
..t2l("omicron", "mupomicron"),
..t2l("phi", "mupvarphi"),
..t2l("phi.alt", "mupphi"),
..t2l("pi", "muppi"),
..t2l("pi.alt", "mupvarpi"),
..t2l("psi", "muppsi"),
..t2l("rho", "muprho"),
..t2l("rho.alt", "mupvarrho"),
..t2l("sigma", "mupsigma"),
..t2l("sigma.alt", "mupvarsigma"),
..t2l("tau", "muptau"),
..t2l("theta", "muptheta"),
..t2l("theta.alt", "mupvartheta"),
..t2l("upsilon", "mupupsilon"),
..t2l("xi", "mupxi"),
..t2l("zeta", "mupzeta"),
..t2l("Alpha", "mupAlpha"),
..t2l("Beta", "mupBeta"),
..t2l("Chi", "mupChi"),
..t2l("Delta", "mupDelta"),
..t2l("Epsilon", "mupEpsilon"),
..t2l("Eta", "mupEta"),
..t2l("Gamma", "mupGamma"),
..t2l("Iota", "mupIota"),
..t2l("Kai", ""),
..t2l("Kappa", "mupKappa"),
..t2l("Lambda", "mupLambda"),
..t2l("Mu", "mupMu"),
..t2l("Nu", "mupNu"),
..t2l("Omega", "mupOmega"),
..t2l("Omicron", "mupOmicron"),
..t2l("Phi", "mupPhi"),
..t2l("Pi", "mupPi"),
..t2l("Psi", "mupPsi"),
..t2l("Rho", "mupRho"),
..t2l("Sigma", "mupSigma"),
..t2l("Tau", "mupTau"),
..t2l("Theta", "mupTheta"),
..t2l("Upsilon", "mupUpsilon"),
..t2l("Xi", "mupXi"),
..t2l("Zeta", "mupZeta"),
..t2l("aleph", "aleph", latexpkg: "MnSymbol"),
..t2l("alef", "aleph", latexpkg: "MnSymbol"),
..t2l("beth", "beth", latexpkg: "MnSymbol"),
..t2l("bet", "beth", latexpkg: "MnSymbol"),
..t2l("gimmel", "gimmel", latexpkg: "MnSymbol"),
..t2l("gimel", "gimmel", latexpkg: "MnSymbol"),
..t2l("daleth", "daleth", latexpkg: "MnSymbol"),
..t2l("dalet", "daleth", latexpkg: "MnSymbol"),
..t2l("shin", ""),
..t2l("AA", "BbbA"),
..t2l("BB", "BbbB"),
..t2l("CC", "BbbC"),
..t2l("DD", "BbbD"),
..t2l("EE", "BbbE"),
..t2l("FF", "BbbF"),
..t2l("GG", "BbbG"),
..t2l("HH", "BbbH"),
..t2l("II", "BbbI"),
..t2l("JJ", "BbbJ"),
..t2l("KK", "BbbK"),
..t2l("LL", "BbbL"),
..t2l("MM", "BbbM"),
..t2l("NN", "BbbN"),
..t2l("OO", "BbbO"),
..t2l("PP", "BbbP"),
..t2l("QQ", "BbbQ"),
..t2l("RR", "BbbR"),
..t2l("SS", "BbbS"),
..t2l("TT", "BbbT"),
..t2l("UU", "BbbU"),
..t2l("VV", "BbbV"),
..t2l("WW", "BbbW"),
..t2l("XX", "BbbX"),
..t2l("YY", "BbbY"),
..t2l("ZZ", "BbbZ"),
..t2l("ell", "ell"),
..t2l("planck", "Planckconst"),
..t2l("planck.reduce", "hslash"),
..t2l("angstrom", "Angstrom"),
..t2l("kelvin", ""),
..t2l("Re", "Re"),
..t2l("Im", "Im"),
..t2l("dotless.i", "imath"),
..t2l("dotless.j", "jmath"),
) |
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/array-22.typ | typst | Other | // Test the `fold` method.
#test(().fold("hi", grid), "hi")
#test((1, 2, 3, 4).fold(0, (s, x) => s + x), 10)
|
https://github.com/zenor0/FZU-report-typst-template | https://raw.githubusercontent.com/zenor0/FZU-report-typst-template/main/fzu-report/utils/numbering-tools.typ | typst | MIT License | #import "packages.typ": int-to-cn-num
#import "states.typ": part-state
#import "fonts.typ": 字体, 字号
#let number-with-circle(num) = "①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳".clusters().at(num - 1, default: "®")
#let chinese-numbering(..nums, location: none, brackets: false) = locate(loc => {
let actual_loc = if location == none { loc } else { location }
if part-state.at(actual_loc) != "附录" {
if nums.pos().len() == 1 {
"第" + int-to-cn-num(nums.pos().first()) + "章"
// int-to-cn-num(nums.pos().first())
} else {
numbering(if brackets { "(1.1)" } else { "1.1" }, ..nums)
}
} else if part-state.at(actual_loc) == "附录" {
if nums.pos().len() == 1 {
"附录 " + numbering("A.1", ..nums)
} else {
numbering(if brackets { "(A.1)" } else { "A.1" }, ..nums)
}
}
}) |
https://github.com/kdkasad/typst-homework-template | https://raw.githubusercontent.com/kdkasad/typst-homework-template/master/khw.typ | typst | BSD 3-Clause "New" or "Revised" License | //
// Kian's Typst homework template
//
// Copyright 2024 <NAME> (<EMAIL>)
//
// This code is made available under the terms of 3-Clause BSD License.
// See the LICENSE file included in this repository.
// SPDX-License-Identifier: BSD-3-Clause
//
#import "@preview/cetz:0.2.2"
#import "@preview/algo:0.3.3": algo, comment, i, d
// Stateful variable to control whether problems
// appear on new pages
#let _khw-newpages = state("_khw:newpages", false)
// Stateful variable to control the default problem name
#let _khw-problem-name = state("_khw:problem-name", "Problem")
// Todo macro
#let todo = box(
stroke: red,
outset: 4pt,
[To do...]
)
// Boxed function
#let boxed = box.with(
stroke: 0.4pt + black,
outset: 3pt
)
// Customized version of algo() from @preview/algo
#let algo = (..args, body) => {
let named = args.named()
// Add bold "procedure" in front of algorithm title
if named.at("header", default: none) == none {
let title = named.at("title")
if type(title) == "string" {
title = underline(smallcaps(title))
}
title = [*procedure* ] + title
named.insert("title", title)
}
args = arguments(..named, ..args.pos())
// Call underlying algo() function from @preview/algo
algo(
block-align: none,
stroke: 0.5pt + black,
row-gutter: 8pt,
indent-guides: 0.4pt + black,
indent-guides-offset: 2pt,
..args,
body + h(1fr) // To make algo box take full text width
)
}
#let call = smallcaps // Helper for calling functions
// Problem function
#let _khw-problem-number = counter("_khw:problem-number")
#let problem = (
name: auto,
newpage: auto,
increment: 1,
label: none,
content
) => {
// Increment counter
_khw-problem-number.update(n => n + increment)
// Page break if requested
context if ((newpage == auto) and (_khw-newpages.get() == true)) or (newpage == true) {
pagebreak(weak: true)
}
// Line above
line(length: 100%, stroke: 0.4pt)
v(-6pt)
// Problem heading/number and text
let problem-numbering = (..nums) => {
if name == auto {
_khw-problem-name.display()
} else {
name
} + numbering(" 1.", ..nums)
}
grid(
columns: (auto, 1fr),
column-gutter: 1em,
[#heading(
numbering: problem-numbering,
outlined: true,
bookmarked: false,
supplement: none,
none
) #label],
content
)
// Line below
v(-6pt)
line(length: 100%, stroke: 0.4pt)
}
// Problem parts function
#let parts = (..args) => {
enum(
numbering: (..nums) => [*#numbering("(a.i)", ..nums)*],
tight: false,
..args.named(),
..args.pos().map(it => {
if type(it) == content {
set enum(numbering: "i)")
block(breakable: false, it)
} else {
it
}
})
)
}
// Document template function
#let khw(
title: none,
course: none,
author: none,
date: datetime.today(),
newpages: false,
problem-name: "Problem",
doc
) = {
// This has to be the first thing in the function body
set page(
paper: "us-letter",
margin: 1in,
numbering: "1",
)
// Save the value of newpages
if newpages {
_khw-newpages.update(true)
}
// Save the value of problem-name
_khw-problem-name.update(problem-name)
set text(
font: "EB Garamond",
size: 11pt,
number-type: "lining",
stylistic-set: 06,
)
set par(
leading: 5pt,
)
// Smaller figure captions
show figure.caption: it => text(size: text.size - 1.5pt, it)
set align(center)
// Title
assert(title != none)
text(size: 18pt, weight: "medium", title)
linebreak()
// Course
if course != none {
text(size: 14pt, course)
linebreak()
}
// Author
if author != none {
author
linebreak()
}
// Date
let nicedate = none
if date != none {
nicedate = date.display("[month repr:long] [day padding:none], [year]")
nicedate
linebreak()
}
parbreak()
// Heading style
show heading.where(level: 1): it => {
text(size: 11pt, weight: "bold", it)
}
// Rest of document
set align(left)
set par(justify: true)
set pagebreak(weak: true)
show "%%author%%": author
show "%%title%%": title
if (date != none) {
show "%%date%%": nicedate
}
doc
}
// Alias for khw
#let doc = khw
// Function to lay out objects in a circle for CeTZ.
// The objects and method used to draw them are completely generic.
//
// Parameters:
//
// radius: length
// Radius of the circle in which to lay out the objects.
//
// items: array
// Array of objects to lay out.
//
// draw_item: function (coordinate, item) => ()
// Callback function used to draw each item.
// This callback takes two arguments (in this order): the coordinate at which
// to draw the object, and the object to draw.
// This function is called for each element of the "items" array.
//
// start: angle [default: 90deg]
// The angle at which the first item will be placed. The angle is measured
// counterclockwise from the east direction.
//
// end: angle [default: auto]
// The angle at which the last item will be placed. The angle is measured
// counterclockwise from the east direction. If set to auto, a default of
// (start + 360deg) is used.
#let radiallayout = (
radius,
items,
draw_item,
start: 90deg,
end: auto,
) => {
if end == auto {
end = start + 360deg
}
import cetz.draw: *
let n = items.len()
let delta = (end - start) / n
for i in range(n) {
let item = items.at(i)
// CeTZ uses (angle, radius) instead of (radius, angle)
draw_item((start + i * delta, radius), item)
}
}
// Function to generate a (di)graph in a radial layout.
// Each node in the graph is placed along a circle, and edges are drawn between
// them as specified.
//
// Parameters:
//
// directed: bool [default: false]
// Whether or not the graph is directed. If true, arrows will be drawn at the
// destination end of each edge.
//
// overlay: bool [default: false]
// Whether to overlap multiple edges between the same nodes. If true, edges
// will be overlapped, i.e. multiple edges will appear as one edge. If false,
// each successive edge will be bent so it is distinguishable from the other
// edges.
//
// nodes: array of strings or array of (string, string) pairs [default: ()]
// Specifies the nodes of the graph.
// Each element describes a node. A single string is used as both the ID and
// the label for the node. A pair of strings, i.e. an array of length 2,
// specifies the ID and the label for the node, in that order.
//
// edges: array of (string, string) or (string, array of strings) pairs [default: ()]
// Specifies the edges of the graph.
// Each element is a pair. The first element of this pair is the ID of the
// source node for an edge. The second element is either the destination
// node's ID, or an array of IDs, in which case an edge will be drawn from the
// source to each destination.
//
// radius: length [default: 1.8cm]
// The radius of the circle on which the nodes will be placed.
//
// radial-start: angle [default: 90deg]
// The angle at which the first node will be placed. The angle is measured
// counterclockwise from the east direction.
//
// radial-end: angle [default: auto]
// The angle at which the last node will be placed. The angle is measured
// counterclockwise from the east direction. If set to auto, a default of
// (radial-start + 360deg) is used.
//
// text-args: dictionary [default: (:)]
// Additional arguments to be passed to Typst's text() function for the node
// labels.
//
// circle-args: dictionary [default: (radius: 0.45cm)]
// Additional arguments to be passed to CeTZ's cetz.draw.circle() function
// used to draw each node.
//
// mark-args: dictionary [default: (symbol: ">", fill: black, scale: 1.4)]
// Additional arguments used to configure the arrowheads on directed edges.
// It is used as follows:
// cetz.draw.set-style(mark: (start: mark-args, end: mark-args))
//
// style-args: dictionary [default: (:)]
// Additional arguments to be passed to CeTZ's cetz.draw.set-style() function.
//
// additional-content: array [default: ()]
// Additional content to be drawn after the graph is drawn. Accepts a code
// block in which cetz.draw.* functions can be called. I.e. this argument
// should be the same as the argument to cetz.canvas().
#let radialgraph = (
directed: false,
overlay: false,
nodes: (),
edges: (),
radius: 1.8cm,
radial-start: 90deg,
radial-end: auto,
text-args: (:),
circle-args: (radius: 0.45cm),
mark-args: (symbol: ">", fill: black, scale: 1.4),
style-args: (:),
additional-content: (),
) => {
// Create drawing
cetz.canvas({
import cetz.draw: *
// Set style of elements
set-style(
stroke: 0.65pt + black, // Default stroke
..style-args, // User-supplied style specifications
circle: circle-args, // Circle style (for nodes)
)
// Convert all nodes in list from strings to tuples (id, label) if necessary
nodes = nodes.map(node-spec => {
if type(node-spec) != array {
(node-spec, node-spec)
} else {
node-spec.slice(0, 2)
}
})
// Function to draw a node.
// Takes a position and a node, which can be a string or a tuple (id, label)
let draw-node = (pos, (node-id, node-label)) => {
circle(pos, name: node-id)
content(node-id, text(..text-args, node-label))
}
// Lay out nodes using radiallayout() and draw-node()
radiallayout(
radius,
nodes,
draw-node,
start: radial-start,
end: radial-end,
)
// Dictionary matrix which represents the graph graph-matrix.at(x).at(y) (x
// and y are node IDs) is a tuple of (count, drawn), where count is the
// number of edges from x to y and drawn is the number of those that have
// been drawn.
let graph-matrix = (:)
for (from-id, _) in nodes {
graph-matrix.insert(from-id, (:))
for (to-id, _) in nodes {
graph-matrix.at(from-id).insert(to-id, (0, 0))
}
}
// Convert all destinations to arrays
edges = edges.map(((src, dst-spec)) => {
if type(dst-spec) != array {
dst-spec = (dst-spec,)
}
(src, dst-spec)
})
// Iterate through edge specifications
for (src, dst-spec) in edges {
// Panic if the source or destinations are not in the list of nodes
let node-ids = nodes.map(it => it.at(0))
for node in (src, ..dst-spec) {
if not node-ids.contains(node) {
panic("Node " + node + "used in edge list but not found in list of nodes")
}
}
// Add each edge to the graph matrix
for dst in dst-spec {
graph-matrix.at(src).at(dst).at(0) += 1
}
}
// Draw edges
for (src, dest-spec) in edges {
for dst in dest-spec {
// Get the number of edges between src and dst. "count" will be the total
// number of edges to be drawn between these nodes (in both directions),
// and "drawn" will be the number already drawn.
let (count, drawn) = graph-matrix.at(src).at(dst)
let (rcount, rdrawn) = graph-matrix.at(dst).at(src)
count += rcount
drawn += rdrawn
// To properly bend edges, we have to make all edges go in the same
// direction. To do this, we make every edge go from the node with the
// lesser ID to the node with the greater ID.
let reverse = false
if src < dst {
(src, dst) = (dst, src)
reverse = true
}
// From here on, we can use "drawn" as the index of the current edge
// being drawn (starting at 0)
// Calculate the bend of this edge
let bend-step = 0.2cm
let (offset, angle) = if calc.rem(count, 2) == 0 {
// Even total number of edges: every edge is bent
let pair = calc.quo(drawn, 2) + 1 // The index of the pair this edge belongs to, starting at 1
if calc.rem(drawn, 2) == 0 {
// Even index edge, bends left
(bend-step * pair, 90deg)
} else {
// Odd index edge, bends right
(bend-step * pair, -90deg)
}
} else {
// Odd total number of edges: first edge is straight, all other edges are bent
let pair = calc.quo(drawn - 1, 2) + 1 // The index of the pair this edge belongs to, starting at 1
if drawn == 0 {
// First edge is straight
(0, 0deg)
} else if calc.rem(drawn - 1, 2) == 0 {
// Even index edge
(bend-step / 2 + bend-step * pair, 90deg)
} else {
// Odd index edge
(bend-step / 2 + bend-step * pair, -90deg)
}
}
if directed {
let key = if reverse {
"start"
} else {
"end"
}
let mark-arg-dict = (start: (), end: ())
mark-arg-dict.insert(key, mark-args)
set-style(mark: mark-arg-dict)
}
// Arc functions fail if the midpoint is on a straight line, so we must check for that
if (overlay == true) or (offset == 0) or (angle == 0) {
line(src, dst)
} else {
// Calculate midpoint of the edge using interpolation coordinates
let midpoint = (
(src, 50%, dst), // Midpoint of the line from src to dst
offset, angle,
dst
)
// Draw an invisible arc from src to dst through the midpoint, and
// find the points where it intersects the borders of src and dst.
intersections("i",
src,
dst,
hide(arc-through(src, midpoint, dst))
)
// Draw the arc between the two intersection points, passing through
// the midpoint.
arc-through("i.0", midpoint, "i.1")
}
// Once we've drawn our edge, increment the drawn count
graph-matrix.at(src).at(dst).at(1) += 1
// If we swapped the src and dst, swap them back before processing the next edge
if reverse {
(src, dst) = (dst, src)
}
}
}
additional-content
})
}
|
https://github.com/Luxzi/doc-templates | https://raw.githubusercontent.com/Luxzi/doc-templates/main/README.md | markdown | MIT License | # doc-templates
Templates for documention (i.e. RFCs, specifications, whitepapers, etc)
## Repository structure
Each directory name is structured as follows:
```
[type]-[technology]-[theme]
```
`[type]` indicates what kind of document the template is for (e.g. RFCs, whitepapers, etc). `[technology]` indicates what technology was used in the template (e.g. Typst, LaTeX, Markdown, etc). `[theme]` indicates what color theme the template uses (e.g. white, black, mocha, etc).
**Please note:** this repository does not contain any guide on how to use the technologies used in each template, please refer to the official documentation for each technology.
## Licensing
Every template in this repository in under an MIT license, feel free to make and share modified versions of these templates. |
https://github.com/floriandejonckheere/utu-thesis | https://raw.githubusercontent.com/floriandejonckheere/utu-thesis/master/thesis/figures/07-proposed-solution/dependency-graph.typ | typst | #import "@preview/cetz:0.2.2": canvas, draw
#v(2em)
#canvas(length: 1cm, {
import draw: *
set-style(content: (padding: .2), stroke: black)
content((0, 2.5), [$G = (V, E)$])
circle((0, 0), radius: .45, stroke: black, name: "v_1")
content((0, 0), [$v_1$])
circle((3, 1), radius: .45, stroke: black, name: "v_2")
content((3, 1), [$v_2$])
let (a, b) = ("v_1", "v_2")
line((a, .45, b), (b, .45, a), name: "e_1")
content(("e_1.start", 1, "e_1.end"), anchor: "south", padding: .5, [$w(e_1)$])
circle((1, -3), radius: .45, stroke: black, name: "v_3")
content((1, -3), [$v_3$])
let (a, b) = ("v_1", "v_3")
line((a, .45, b), (b, .45, a), name: "e_2")
content(("e_2.start", 1, "e_2.end"), anchor: "east", padding: .5, [$w(e_2)$])
let (a, b) = ("v_2", "v_3")
line((a, .45, b), (b, .45, a), name: "e_3")
content(("e_3.start", 1.5, "e_3.end"), anchor: "west", padding: .5, [$w(e_3)$])
circle((5, -4), radius: .45, stroke: black, name: "v_4")
content((5, -4), [$v_4$])
let (a, b) = ("v_3", "v_4")
line((a, .45, b), (b, .45, a), name: "e_4")
content(("e_4.start", 1.5, "e_4.end"), anchor: "north", padding: .5, [$w(e_4)$])
circle((9, -3), radius: .45, stroke: black, name: "v_5")
content((9, -3), [$v_5$])
let (a, b) = ("v_4", "v_5")
line((a, .45, b), (b, .45, a), name: "e_5")
content(("e_5.start", 1.5, "e_5.end"), anchor: "north", padding: .5, [$w(e_5)$])
circle((7, -1), radius: .45, stroke: black, name: "v_6")
content((7, -1), [$v_6$])
let (a, b) = ("v_5", "v_6")
line((a, .45, b), (b, .45, a), name: "e_6")
content(("e_6.start", 1.4, "e_6.end"), anchor: "north", padding: .5, [$w(e_6)$])
circle((10, 0), radius: .45, stroke: black, name: "v_7")
content((10, 0), [$v_7$])
let (a, b) = ("v_5", "v_7")
line((a, .45, b), (b, .45, a), name: "e_7")
content(("e_7.start", 1.2, "e_7.end"), anchor: "west", padding: .5, [$w(e_4)$])
circle((8, -6), radius: .45, stroke: black, name: "v_8")
content((8, -6), [$v_8$])
let (a, b) = ("v_4", "v_8")
line((a, .45, b), (b, .45, a), name: "e_8")
content(("e_8.start", 1, "e_8.end"), anchor: "north", padding: .5, [$w(e_8)$])
})
#v(2em)
|
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/037_Ravnica%20Allegiance.typ | typst | #import "@local/mtgset:0.1.0": conf
#show: doc => conf("Ravnica Allegiance", doc)
#include "./037 - Ravnica Allegiance/001_The Illusions of Child's Play.typ"
#include "./037 - Ravnica Allegiance/002_Rage of the Unsung.typ"
#include "./037 - Ravnica Allegiance/003_The Principles of Unnatural Selection.typ"
#include "./037 - Ravnica Allegiance/004_The Ledger of Hidden Fortunes.typ"
#include "./037 - Ravnica Allegiance/005_The Gathering Storm: Chapter 11.typ"
#include "./037 - Ravnica Allegiance/006_The Gathering Storm: Chapter 12.typ"
#include "./037 - Ravnica Allegiance/007_The Gathering Storm: Chapter 13.typ"
#include "./037 - Ravnica Allegiance/008_The Gathering Storm: Chapter 14.typ"
#include "./037 - Ravnica Allegiance/009_The Gathering Storm: Chapter 15.typ"
#include "./037 - Ravnica Allegiance/010_The Gathering Storm: Chapter 16.typ"
#include "./037 - Ravnica Allegiance/011_The Gathering Storm: Chapter 17.typ"
#include "./037 - Ravnica Allegiance/012_The Gathering Storm: Chapter 18.typ"
#include "./037 - Ravnica Allegiance/013_The Gathering Storm: Chapter 19.typ"
#include "./037 - Ravnica Allegiance/014_The Gathering Storm: Chapter 20.typ"
|
|
https://github.com/yhtq/Notes | https://raw.githubusercontent.com/yhtq/Notes/main/数理逻辑/作业/ml-3_2-hw.typ | typst | #import "../../template.typ": proof, note, corollary, lemma, theorem, definition, example, remark
#import "../../template.typ": *
#import "../main.typ": not1, True, False, infer
#import "../main.typ": *
#show: note.with(
title: "作业3_1",
author: "YHTQ",
date: datetime.today().display(),
logo: none,
withOutlined : false,
withTitle : false,
withHeadingNumbering: false
)
#set heading(numbering:
(..nums) =>
{
let nums1 = nums.pos()
nums1.insert(0, 6)
numbering("1.1.(a)", ..nums1)
}
)
= #empty
- $v models calA and calB := v models calA$ 且 $v models calB$
- $v models calA or calB := v models calA$ 或 $v models calB$
- $v models exists x_i calA(x_i) := $ 存在一个与 $v$ $i-$ 等值的赋值 $v'$,使得 $v' models calA(x_i)$
= #empty
$
&"match" calA(t) with\
&| A_m^n (a_1, ..., a_n) => v models calA(t) &&<=> overline(A_m^n)(v(a_1), ..., v(a_n)) = T\
&space &&<=> overline(A_m^n)(v'(a_1 (x_i \/ t)), ..., v'(a_n (x_i \/ t))) = T "(递归条件)"\
&space &&<=> v models A_m^n (a_1(x_i \/ t), ..., a_n (x_i \/ t)) \
&space &&<=> v models calA(t)\
&| not1 calB(x_i) => "易证"\
&| calB(x_i) -> calC(x_i) => "易证"\
&| forall x_i calB(x_i) => "替换只替换自由变元,显然"\
&| forall x_j calB(x_i) => v' models calA(x_i) &&<=> "forall" d_i in D_I, v' models calB(x_i)(x_j \/ d_i)\
$
#lemmaLinear[][
$t$ 在 $calB(x_i)(x_j \/ d_i)$ 对 $x_i$ 自由,且 $calB(x_i)(x_j \/ d_i)(x_i \/ t) = calB(t)(x_j \/ d_i)$
]
#proof[
- 假设 $t$ 中有 $x_j$ 自由出现,那么由 $t$ 对 $x_i$ 自由的定义,$x_i$ 将不能在 $calB(x_i)$ 中出现,结论显然。
- 否则,$t$ 中无 $x_j$ 自由出现,不难验证 $t$ 在 $calB(x_i)(x_j \/ d_i)$ 对 $x_i$ 自由等价于 $t$ 在 $calB(x_i)$ 对 $x_i$ 自由,立刻由条件保证,而替换顺序的交换是容易的。
]
由引理及归纳假设:
$
&"forall" d_i in D_I, v models calB(x_i)(x_j \/ d_i)(x_i \/ t) \
&<=> "forall" d_i in D_I, v models calB(x_i)(x_j \/ d_i)(x_i \/ t) \
&<=> "forall" d_i in D_I, v models calB(t)(x_j \/ d_i)\
&<=> v models forall x_j calB(t)
$
= #empty
解释为:
$
forall x, y: ZZ, (x - y < 0 -> x < y)
$
为真。定义另一个解释 $I'$,其中 $overline(f_1^2)(a, b) = a * b$,其它与 $I$ 相同,则公式解释为:
$
forall x, y: ZZ, (x * y < 0 -> x < y)
$
为假。
第二个公式解释为:
$
forall x_1: ZZ, x_1 - x_2 < x_3
$
断言所有赋值都不可能使其为真。事实上,任取赋值 $v$,若:
$
v models forall x_1: ZZ, x_1 - x_2 < x_3
$
由任意量词的可满足性定义,取 $v'(x_1) = v(x_2) + v(x_3) + 1$ 是一个 $i-$ 等值的赋值,不难验证:
$
v' notModels x_1 - x_2 < x_3
$
进而:
$
v notModels forall x_1: ZZ, x_1 - x_2 < x_3
$
下一个公式解释为:
$
forall x_1: ZZ, 0 - x_1 < 0
$
显然为假,由任意量词的可满足性定义,可以取赋值 $v'$ 使得 $v'(x_1) = 0$,容易验证为假
= #empty
取论域为 $ZZ$,$overline(A_1^1) (x) := x > 0, overline(f_1^1) (x) = -x$,则公式解释为:
$
forall x: ZZ(x > 0 -> -x > 0)
$
显然为假
= #empty
在算术解释中,公式解释为:
$
forall x_1: NN, x_1 x_2 = x_3
$
取赋值 $v(x_2) = 0, v(x_3) = 0$,则前式为真\
取赋值 $v(x_2) = 0, v(x_3) = 1$,则前式为假 |
|
https://github.com/typst/templates | https://raw.githubusercontent.com/typst/templates/main/cereal-words/lib.typ | typst | MIT No Attribution | // The game board.
#let board = ```
D D E L I V E R Y P
O P N G K G J G R L
C R E A T U R E S E
U E V L K H F G A U
M G R Y C E Z G M C
E L J T R I L A F T
N M H Q A E H M H D
T I F T K I X E P C
S M O H X I N T V S
K O R O H U A U A Q
```.text.split("\n").map(line => line.split().map(str.trim))
// Did you really think the words would be here in plain text?
#let solution = (
134676999, 220725935, 104989125, 51446073, 137429505,
29688040, 46268699, 27656404, 176095840, 174326373,
)
// The movement directions.
#let dirs = (
(-1, 0), (-1, -1), (0, -1), (1, -1),
( 1, 0), ( 1, 1), (0, 1), (-1, 1),
)
// The tile and board sizes.
#let size = 2em
#let w = board.first().len()
#let h = board.len()
// Maps from letters to their occurances.
#let letters = (:)
#for (y, row) in board.enumerate() {
for (x, c) in row.enumerate() {
if c in letters {
letters.at(c).push((x, y))
} else {
letters.insert(c, ((x, y),))
}
}
}
// Finds a word in the board if it exists.
#let find-word(word) = {
let a = word.first()
let b = word.last()
for start in letters.at(a, default: ()) {
for (dx, dy) in dirs {
let ok = true
let (x, y) = start
for c in word {
if board.at(y, default: ()).at(x, default: "") != c {
ok = false
break
}
x += dx
y += dy
}
if ok {
return (start, (x - dx, y - dy))
}
}
}
}
// Renders the letter grid.
#let render-board = {
place(grid(
columns: w * (size,),
rows: h * (size,),
..board.flatten().map(align.with(center + horizon)),
))
}
// Renders a line through a word.
#let render-mark((x1, y1), (x2, y2)) = {
let extend = size / 4
let c = size / 2
let dx = x2 - x1
let dy = y2 - y1
let norm = calc.sqrt(calc.pow(dx, 2) + calc.pow(dy, 2))
let hx = extend * dx / norm
let hy = extend * dy / norm
let start = (x1 * size + c - hx, y1 * size + c - hy)
let end = (x2 * size + c + hx, y2 * size + c + hy)
place(line(start: start, end: end))
}
// Parses the document's body into an array of words.
#let parse-input(body) = {
let extract(it) = {
""
if it == [ ] {
" "
} else if it.func() == text {
it.text
} else if it.func() == [].func() {
it.children.map(extract).join()
}
}
extract(body)
.split(regex("\s+"))
.filter(s => s.len() >= 3)
.map(upper)
}
// Hash a word.
#let hash(word) = {
let s1 = 1
let s2 = 0
for c in word {
s1 = calc.rem(s1 + str.to-unicode(c), 65521)
s2 = calc.rem((s2 + s1), 65521)
}
s2 * calc.pow(2, 16) + s1
}
// Displays an informative popup.
#let popup(main, sub: none) = place(center + horizon, rect(
width: 5.7 * size,
height: 1.7 * size,
fill: black,
stroke: 6pt + white,
{
set text(1.25em, fill: white)
text(1em, main)
if sub != none {
v(0.4em, weak: true)
text(0.5em, sub)
}
}
))
// The game template.
#let game(body) = {
set page(width: (w + 1) * size, height: (h + 2) * size, margin: size / 2)
set text(font: "VG5000", 25pt)
set line(stroke: 4pt + green)
align(center, text(0.8em)[Find the hidden words!])
v(0.5em)
render-board
let words = parse-input(body).dedup()
let hashes = words.map(hash)
let found = hashes.filter(hash => hash in solution)
let got = found.len()
let total = solution.len()
for (word, hash) in words.zip(hashes) {
if hash not in solution { continue }
let position = find-word(word)
if position != none {
render-mark(..position)
}
}
place(bottom + center, text(0.5em)[#got / #total])
if got == total or 266011376 in hashes {
popup(sub: [with #words.len() word#if words.len() > 1 [s]])[You win!]
}
}
|
https://github.com/justinvulz/typst_packages | https://raw.githubusercontent.com/justinvulz/typst_packages/main/test.typ | typst | // #show regex("\p{script=Han}"):it=>[
// #set text(font: ("Times New Roman","DFKai-SB"))
// #text(weight: "bold")[#it]
// ]
#set text(font: ("Times New Roman","DFKai-SB"))
#let f(n) ={n}
#let t = (f)(3)
#t |
|
https://github.com/SWATEngineering/Docs | https://raw.githubusercontent.com/SWATEngineering/Docs/main/src/2_RTB/VerbaliInterni/VerbaleInterno_231124/content.typ | typst | MIT License | #import "meta.typ": inizio_incontro, fine_incontro, luogo_incontro
#import "functions.typ": glossary, team
#let participants = csv("participants.csv")
= Partecipanti
/ Inizio incontro: #inizio_incontro
/ Fine incontro: #fine_incontro
/ Luogo incontro: #luogo_incontro
#table(
columns: (3fr, 1fr),
[*Nome*], [*Durata presenza*],
..participants.flatten()
)
= Sintesi Elaborazione Incontro
== Assegnazione dei ruoli
Su proposta dei componenti è stata assegnata questa distribuzione dei ruoli:
- Responsabile: <NAME>;
- Amministratore: <NAME>;
- Analista: <NAME>;
- Verificatore: <NAME>;
- Programmatore: <NAME>;
- Programmatore: <NAME>.
Il ruolo di Progettista non è stato assegnato, in quanto per il momento ha operatività limitata.
La presenza di due Programmatori è dovuta al fatto che il Team in accordo con la Proponente vuole sviluppare una prima versione del PoC entro la fine dello sprint corrente.
== Cambio di ruoli settimanale
Per favorire una rotazione più rapida e un carico di lavoro più omogeneo il team ha deciso di introdurre la possibilità di cambiare i ruoli una volta raggiunta la metà temporale di ogni sprint. Nell'ottica dello sprint iniziato in data odierna, il cambio dei ruoli avverrà ipoteticamente venerdì 1 Dicembre.
Si precisa che il cambio dei ruoli è opzionale e non necessariamente riguarda la totalità dei ruoli e dei membri.
I membri coinvolti nello scambio devono però aver almeno concluso le issue assegnate e già cominciate.
== Sprint Planning
Al termine dell'incontro il team ha proceduto alla creazione dello Sprint Backlog.
Inizialmente si sono rilevate le nuove issue a seguito dell'incontro con la proponente avvenuto la mattinata stessa e sono state inserite nel Product Backlog.
Successivamente le issue sono state selezionate e inserite nello Sprint Backlog e ad ognuna è stata assegnata size e priority.
Sulla base della somma delle size delle issues selezionate il nuovo sprint risulta decisamente più corposo di quello precedente.
Questo è in linea con l'intenzione di preparare tutto l'occorrente per poter richiedere la prima revisione RTB non oltre il 18 dicembre.
Il Processo di selezione delle issues si è basato sull'obiettivo dello sprint rilevato con la Proponente, ovvero il completamento del PoC: ciò nonostante non si può dire che lo sprint sia univocamente focalizzato su di esso, in quanto il team si impegnerà anche a portare avanti la stesura della parte documentale relativa alla RTB.
|
https://github.com/ymgyt/techbook | https://raw.githubusercontent.com/ymgyt/techbook/master/programmings/js/typescript/specification/environment_variable.md | markdown | # Environment variable
```typescript
const v = process.env.ENV_KEY ?? "default"
```
* `process.env` objectに入っている。
* 設定されていない場合はobjectに対する存在しないproperty accessとしてundefinedが返る
|
|
https://github.com/jamesrswift/chemicoms-paper | https://raw.githubusercontent.com/jamesrswift/chemicoms-paper/main/src/elements/header-block.typ | typst |
#let header-block(
args
) = block(
text(weight: 200, 24pt, fill: white, args.header.article-type),
fill: args.header.article-color,
width: 100% ,
inset: 10pt,
radius: 2pt
) |
|
https://github.com/sthenic/technogram | https://raw.githubusercontent.com/sthenic/technogram/main/src/palette.typ | typst | MIT License | /* We keep the default palette as a noncontextual object. */
#let DEFAULT-PALETTE = (
primary: rgb("#005050"),
secondary: rgb("#D2E6E6"),
background: rgb("#FFFFFF"),
note-header: rgb("#005050"),
note-body: rgb("#D2E6E6"),
tip-header: rgb("#005050"),
tip-body: rgb("#D2E6E6"),
important-header: rgb("#BF2629"),
important-body: rgb("#FDF3F2"),
warning-header: rgb("#E97211"),
warning-body: rgb("#FFEFE1"),
example-header: rgb("#005050"),
example-body: rgb("#D2E6E6"),
release-header: rgb("#005050"),
release-body: rgb("#D2E6E6"),
display-header: rgb("#005050"),
display-body: luma(240),
)
/* The global palette state. */
#let palette = state("palette", DEFAULT-PALETTE)
/* Convenience function to override any number of entries in the state. */
#let update-palette(..args) = context {
palette.update(palette.get() + args.named())
}
/* Convenience function to avoid exporting the state variable directly. */
#let get-palette() = palette.get()
/* Convenience function to generate a somewhat unified palette for the admonitions. */
#let generate-admonition-palette(primary, secondary) = {
/* TODO: Explicit for now, warning keeps its color. */
update-palette(
note-header: primary,
note-body: secondary,
tip-header: primary,
tip-body: secondary,
important-header: primary,
important-body: secondary,
example-header: primary,
example-body: secondary,
release-header: primary,
release-body: secondary,
display-header: primary,
)
}
/* Table fill pattern */
#let table-fill = (_, y) => {
if calc.even(y) and y > 0 { luma(240) } else { white }
}
/* Table stroke pattern */
#let table-stroke = (x, y) => (
left: 0pt,
right: 0pt,
top: if y == 0 { 1.2pt } else if y == 1 { 0.7pt } else { 0pt },
bottom: 1.2pt,
)
|
https://github.com/Az-21/typst-components | https://raw.githubusercontent.com/Az-21/typst-components/main/style/README.md | markdown | Creative Commons Zero v1.0 Universal | # Override default styles
## Installation
Download and place this specific `style` folder in
```sh
%LocalAppData%\typst\packages\local
```
## Usage
```typst
#import "@local/style:1.0.0": *
#show: style
```
|
https://github.com/xingjian-zhang/typst2img | https://raw.githubusercontent.com/xingjian-zhang/typst2img/main/output/general_relativity.typ | typst | #let display(body) = context {
set page(width: auto, height: auto, margin: (x: 20pt, y: 20pt))
align([#body], center + horizon)
}
#display[$ G_(mu nu) + Lambda g_(mu nu) = kappa T_(mu nu) $] |
|
https://github.com/HollowNumber/DDU-Rapport-Template | https://raw.githubusercontent.com/HollowNumber/DDU-Rapport-Template/main/src/format.typ | typst | #import "./lib/recursive_count.typ": *
#let rapport(
titel: "",
undertitel: "",
sidehoved: [],
abstract: [],
forfatter: (),
vejleder: (),
logo: none,
periode: "",
toc: true,
tof: false,
tot: false,
acknowledgements: [],
body,
) = {
// Indstil dokumentets grundlæggende egenskaber.
set document(author: forfatter.map(a => a.name), title: titel)
set text(font: "arial", lang: "da", ligatures: true)
show heading: set text(font: "Neo Sans Pro", fill: rgb(50, 55, 152))
show raw: set text(font: "Monaspace Neon")
set smartquote(quotes: "»«")
set page(numbering: "I", number-align: right)
show math.equation: set text(weight: 400)
set heading(numbering: "1.1")
show figure: set block(breakable: true)
// Indsæt indgående subheadings, begyndende på niveau 3.
show quote: it => {
layout(size => {
style(styles => {
let (height, width) = measure(block(width: size.width, it.body),styles)
let gridContent = (
[#pad(line(
angle: 90deg, stroke: 1pt + rgb(50, 55, 152),
length: height
))],
[#it.body]
)
if it.has("block") {
if it.has("attribution") {
let attribution = it.attribution
// Add horziontal line to the left of the quote
gridContent.push([])
gridContent.push([#align(end)[#v(-0.2em)#h(width)--- #text(0.8em, attribution)]])
}
grid(columns: 2, ..gridContent)
} else {
["#it.body"]
}
})
})
}
// titel side.
// Siden kan indeholde et logo, hvis du angiver et logo med `logo: "logo.png"`.
// fjern header
v(5.6fr)
if logo != none {
align(center, image(logo, width: 75%))
}
v(9.6fr)
text(2em, weight: 700, [*#titel*: ])
text(1.5em, weight: 600, undertitel)
pad(
top: 0.5em,
right: 20%,
[Fra #periode]
)
v(-0.8em)
line(length: 75%, stroke: rgb(50, 55, 152))
// forfatter information.
pad(
top: 0.7em,
right: 20%,
grid(
columns: (1fr,) * calc.min(3, forfatter.len()),
gutter: 1em,
..forfatter.map(author => align(start)[
*#author.name* \
#text(0.8em, author.affiliation)
]),
),
)
v(1.5em)
// vejleder information.
[#if vejleder.len() < 2 [*Vejleder*: ] else [*Vejledere*: ]]
v(-0.8em)
line(length: 25%, stroke: rgb(50, 55, 152))
pad(
top: 0.1em,
right: 20%,
grid(
columns: (1fr,) * calc.min(3, vejleder.len()),
gutter: 1em,
..vejleder.map(teacher => align(start)[
*#teacher.name * (#text(0.75em, teacher.lectio)) \
#text(0.8em, teacher.affiliation)
]),
))
v(2.4fr)
let anslag = recursive_count(body)
[*Anslag*: #anslag #text(0.75em,[(svarende til #calc.floor(recursive_count(body) / 2400) ns)])]
v(3fr)
// Underskrift
pad(
top: 0.7em,
right: 20%,
align(start)[
#grid(
columns: (1fr,) * calc.min(3, forfatter.len()),
gutter: 1em,
..forfatter.map(author => align(center)[
#text(0.75em, [*Underskrift*]): #box(width: 1fr, repeat[\_])
])
)
],
)
show page: set page(header: sidehoved)
pagebreak()
// Abstract.
if abstract != [] {
v(1fr)
align(center)[
#heading(
outlined: false,
numbering: none,
text(0.85em, smallcaps[Resumé]),
)
#abstract
]
v(1.618fr)
pagebreak()
}
// Acknowledgements.
if acknowledgements != [] {
heading(outlined: false,numbering: none,text(0.85em, smallcaps[Ankerkendelser]))
// Authors
v(1em)
[#if forfatter.len() > 1 [*Forfattere*: ] else [*Forfatter*: ]]
v(-0.8em)
line(length: 25%, stroke: rgb(50, 55, 152))
for dict in forfatter {
parbreak()
[*#dict.name*, #text(0.75em, dict.affiliation_short)]
}
v(1em)
par(acknowledgements, justify: true)
v(1.618fr)
pagebreak()
}
show outline.entry.where(level: 1): it => {
v(12pt, weak: true)
strong(it)
}
// Table of contents.
if toc {
v(5em)
outline(depth: 3, indent: auto)
pagebreak()
}
if tof {
v(5em)
outline(
title: [Figurer],
target: figure.where(kind: image).or(figure.where(kind: table)).or(figure.where(kind: raw))
)
pagebreak()
}
if tot {
v(5em)
outline(
title: [Tabeller],
target: figure.where(kind: table)
)
pagebreak()
}
// Glossary.
v(5em)
include "chapters/ordliste.typ"
pagebreak()
// Main body.
set par(justify: true, first-line-indent: 1em)
set page(columns: 2, numbering: "1 аf 1", number-align: right)
counter(page).update(1)
body
}
|
|
https://github.com/mem-courses/linear-algebra | https://raw.githubusercontent.com/mem-courses/linear-algebra/main/note/5.线性空间.typ | typst | #import "../template.typ": *
#show: project.with(
title: "Linear Algebra #5",
authors: (
(name: "<NAME>", email: "<EMAIL>", phone: "3230104585"),
),
date: "December 3, 2023",
)
#let alpha = math.bold(math.alpha)
#let beta = math.bold(math.beta)
#let gamma = math.bold(math.gamma)
#let theta = math.bold(math.theta)
#let eta = math.bold(math.eta)
#let nu = math.bold(math.nu)
#let xi = math.bold(math.xi)
#let ds = math.dots.c
#let TT = math.upright("T")
= 线性空间
== 运算的刻画
1. 设 $X,Y,Z$ 为三个非空集合,若 $phi:sp X times Y -> Z$ 是一个在积集 $X times Y$ 上,取值于非空集合 $Z$ 中的映射.则称 $phi$ 是一个从集合 $X,Y$ 到集合 $Z$ 的 *二元运算*.称映射 $phi:sp X times X -> X$ 是一个定义在集合 $X$ 上的二元运算.
2. 设 $PP$ 是数域,$X$ 为一个非空集合,称任何一个定义在 $PP times X$ 上,取值于 $X$ 中的映射 $phi$ 为 $X$ 的一个关于 $PP$ 的 *数乘运算*.通常,若 $x,y in X$,$c in PP$,满足 $y = phi(c,x)$,则记 $y=c x$.
== 线性空间的定义
设 $PP$ 是一个数域(其中元素用 $a,b,c,dots$ 表示),$V$ 是一个非空集合(其中元素用 $alpha,beta,gamma,dots$ 表示,一般称为向量),如果下列条件满足,则称 $V$ 为数域 $PP$ 上的一个线性空间,当且仅当定义两种运算:
1. 加法封闭:$forall alpha,beta in V,sp exists "唯一的" gamma in V st gamma = alpha + beta$.
2. 数乘封闭:$forall alpha in V, sp forall k in PP, sp exists "唯一的" gamma in V st gamma = k alpha$.
且这两种运算还要满足下面八条运算规律:
1. 加法交换律:$alpha+beta = beta+alpha$;
2. 加法结合律:$(alpha+beta)+gamma = alpha+(beta+gamma)$;
3. 零向量:$exists theta in V st forall alpha in V, alpha + theta = theta + alpha$;
4. 负向量:$forall alpha in V , sp exists beta in V st alpha + beta = theta$;
5. $k(alpha + beta) = k alpha + k beta$;
6. $(k + l)alpha = k alpha + l alpha$;
7. $(k l) alpha = k (l alpha)$;
8. $1 dot alpha = alpha$.
这时,记这个数域 $PP$ 上的线性空间为 ${V,+,dot,PP}$.
#note[
#def[例]
1. 记 $P[x]_n$ 为定义为数域 $PP$ 上的最高次幂小于 $n$ 的多项式,则 $P[x]_n$ 的多项式加法和数乘运算可以构成数域 $PP$ 上的线性空间.\
2. 复数域 $CC$ 关于数的加法和乘法,可以构成实数域 $RR$ 上的线性空间.\
3. 实数域 $RR$ 关于数的加法和乘法,可以构成有理数域 $QQ$ 上的线性空间.\
]
#warn[判断是否是线性空间要注意指定数域 $PP$.]
#def[定理1]设 $V$ 是数域 $PP$ 上的一个线性空间,则 (1) 零向量 $theta$ 唯一;(2) 每个向量的负向量唯一.
== 线性组合与线性表示
设 $%alpha_1,alpha_2,dots.c,alpha_s$ 是 $V$ 中的 $s$ 个向量,$k_1,k_2,dots.c,k_s$ 是数域 $PP$ 中的任意 $s$ 个数,则称 $k_1 alpha_1 + k_2 alpha_2 + dots.c + k_s alpha_s$ 为向量组 $alpha_1,alpha_2,dots.c,alpha_s$ 的一个 *线性组合*.
若对 $beta in V$,当且仅当存在数 $c_1,c_2,dots.c,c_s in PP st beta = c_1 alpha_1 + c_2 alpha_2 + dots.c + c_s alpha_s$ 时,称 $beta$ 可由向量组 $alpha_1,alpha_2, dots.c, alpha_s$ *线性表示*.
#note[
1. 这两条用来定义 *一个* 向量与 *一组* 向量的联系.
2. 对于向量组 $alpha_1,alpha_2,dots.c,alpha_s$ 的所有线性组合,如果其中有一个等于 $beta$,则 $beta$ 可被该向量组线性表示,否则不行.
]
=== 与线性方程组的联系
设向量 $beta = display(mat(b_1,b_2,dots.c,b_n))^TT$ 和向量组 $alpha_i = display(mat(a_(1 i),a_(2 i),dots.c,a_(n i)))^TT,sp i = 1,2,dots.c,s$.则:
$beta$ 能被向量组 $alpha_1,alpha_2,dots.c,alpha_s$ 线性表示
$quad quad<==>$ 能找到一组数 $k_1,k_2,dots.c,k_s in PP$ 使得 $beta=k_1 alpha_1 + k_2 alpha_2 + dots.c + k_s alpha_s$.
$quad quad <==>$ $display(k_1 mat(a_11;a_21;dots.v;a_(n 1)) + k_2 mat(a_12;a_22;dots.v;a_(n 2)) + dots.c + k_s mat(a_(1 s);a_(2 s);dots.v;a_(n s)) = mat(b_1;b_2;dots.v;b_n))$.
$quad quad <==>$ 线性方程组 $bold(A) X = beta$ 有解,其中 $X$ = $display(mat(k_1;k_2;dots.v;k_s))$.
$quad quad <==>$ $r(bold(A)) = r(overline(bold(A)))$,其中 $overline(bold(A)) = display(mat(bold(A), dots.v ,beta))$.
特别地,当 $r(bold(A)) = r(overline(bold(A))) = s$ 时,表示方法唯一;当 $r(bold(A)) = r(overline(bold(A))) < s$ 时,表示方法有无穷多种.
#note[
1. $r(bold(A)) < r(overline(bold(A))) <=>$ $beta$ 不能被 $seqn(alpha,s)$ 线性表示;
2. $r(bold(A)) = r(overline(bold(A))) < s <=>$ $seqn(alpha,s)$ 是线性相关的向量组.
]
== 线性相关与线性无关
设 $alpha_1,alpha_2,dots.c,alpha_s in V$,如果存在一组不全为 $0$ 的数域 $PP$ 中的数 $k_1,k_2,dots.c,k_s$ 使得 $ k_1 alpha_1 + k_2 alpha_2 + dots.c + k_s alpha_s = theta $ 则称向量组 $alpha_1,alpha_2,dots.c,alpha_s$ *线性相关*,否则称该向量组 *线性无关*.
=== 性质
#def[性质1]1. 部分相关 $==>$ 整体相关\
#deft[性质1]2. 整体无关 $==>$ 部分无关\
#deft[性质1]3. 原来相关 $==>$ 缩短相关\
#deft[性质1]4. 原来无关 $==>$ 增长无关\
#def[性质2]含零向量的向量组必线性相关.
#def[性质3]1. 对于单个向量 $alpha$ 构成的向量组,它线性无关当且仅当 $alpha != theta$.\
#deft[性质3]2. 两个非零向量 $alpha,beta$ 线性相关,则必存在 $0 != k in PP st alpha + k beta = theta$.
#def[性质4]1. 非零向量 $alpha,beta in RR^2$ 线性相关 $=>$ $alpha,beta$ 共线或平行;线性无关 $=>$ $alpha,beta$ 相交.\
#deft[性质4]2. 非零向量 $alpha,beta,gamma in RR^3$ 线性相关 $=>$ $alpha,beta,gamma$ 共面;$alpha,beta,gamma$ 线性无关 $=>$ $alpha,beta,gamma$ 异面.
=== 与线性方程组的联系
设 $alpha_1,alpha_2,dots.c,alpha_s in PP^n$ 线性相关
$quad quad <==>$ 存在一组不全为零的数 $k_1,k_2,dots.c,k_s in PP$ 使得 $k_1 alpha_1 + k_2 alpha_2 + dots.c + k_s alpha_s = theta$.
$quad quad <==>$ $display(k_1 mat(a_11;a_21;dots.v;a_(n 1)) + k_2 mat(a_12;a_22;dots.v;a_(n 2)) + dots.c + k_s mat(a_(1 s);a_(2 s);dots.v;a_(n s)) = mat(0;0;dots.v;0))$
$quad quad <==>$ $bold(A) bold(X) = theta$ 有非零解,其中 $X$ = $display(mat(k_1;k_2;dots.v;k_s))$.
$quad quad <==>$ $r(bold(A)_(n times s)) < s$(秩小于向量组中向量的个数).
也就是说:
- $alpha_1,alpha_2,dots.c,alpha_s$ 线性相关 $<==>$ $bold(A)_(n times s) bold(X) = 0$ 有非零解 $<==>$ $R(bold(A)_(n times s)) < s$
- $alpha_1,alpha_2,dots.c,alpha_s$ 线性无关 $<==>$ $bold(A)_(n times s) bold(X) = 0$ 只有零解 $<==>$ $R(bold(A)_(n times s)) = s$
特别的,对于 $PP^m$ 中任意 $n$ 个向量组成的向量组 $alpha_1,alpha_2,dots.c,alpha_n$,他们线性无关当且仅当 $|bold(A)| != 0$ $<=>$ $r(bold(A)) = n$.
=== 与线性表示的关系
#def[性质1]向量组 $seqn(alpha,s)$ 线性相关 $<=>$ 其中至少有一个向量可以被其余向量线性表示.
#warn[不是每一个向量都可以被其余向量线性表示哦!]
#def[性质2]若向量组 $seqn(alpha,s)$ 线性无关而向量组 $seqn(alpha,s),beta$ 线性相关 $=>$ 向量 $beta$ 一定可以被向量组 $seqn(alpha,s)$ 线性表示,且表示方法唯一.
#prof[
#def[证明]因为向量组 $seqn(alpha,s),beta$ 线性相关,故存在一组 $k_1,k_2,dots.c,k_s,k_0$ 使得 $ k_1 alpha_1 + k_2 alpha_2 + dots.c + k_s alpha_s + k_0 beta = theta $反设 $k_0 = 0$,则 $k_0 beta = theta$,与 $alpha_1,alpha_2,dots.c,alpha_s$ 线性无关矛盾;所以 $k_0!=0$,则存在一组 $ beta = -1/k_0 (k_1 alpha_1 + k_2 alpha_2 + dots.c + k_s alpha_s) $
再证唯一性:若存在
$
&beta = t_1 alpha_1 + t_2 alpha_2 + dots.c + t_s alpha_s = l_1 alpha_1 + l_2 alpha_2 + dots.c + l_s alpha_s\
=> &(t_1-l_1) alpha_1 + (t_2 - l_2) alpha_2 + dots.c (t_s - l_s) alpha_s = theta
$
其中 $t_1,t_2,dots.c,t_s$ 与 $l_1,l_2,dots.c,l_s$ 不完全先沟通,与 $alpha_1,alpha_2,dots.c,alpha_s$ 线性无关矛盾,故唯一性成立.
]
== 向量组的线性表示
设数域 $PP$ 上的线性空间 $V$ 中有两个向量组 (I) $alpha_1,alpha_2,dots.c,alpha_r$ 和 (II) $beta_1,beta_2,dots.c,beta_s$.如果向量组 (I) 中的每个向量都可被向量组 (II) 线性表示,则称向量组 (I) 可被向量组 (II) 线性表示.
由定义设
$
alpha_j
= m_(1 j) beta_1 + m_(2 j) beta_2 + dots.c + m_(s j) beta_s
= mat(beta_1, beta_2, dots.c, beta_s) mat(m_(1 j); m_(2 j); dots.v; m_(s j))sp (j = 1,dots.c,r)\
$
称 $display(mat(beta_1, beta_2, dots.c, beta_s))$ 是形式矩阵.形式矩阵的运算具有:
- *结合律*:$display( mat(beta_1,beta_2,dots.c,beta_t) (bold(A B)) = (mat(beta_1,beta_2,dots.c,beta_t) bold(A)) bold(B) )$;
- *传递性*:若 $display( mat(alpha_1,alpha_2,dots.c,alpha_t) = mat(beta_1,beta_2,dots.c,beta_t) bold(C) )$ 且 $display( mat(beta_1,beta_2,dots.c,beta_t) = mat(gamma_1,gamma_2,dots.c,gamma_t) bold(D) )$,那么 $display( mat(alpha_1,alpha_2,dots.c,alpha_t) = mat(gamma_1,gamma_2,dots.c,gamma_t) bold(D C) )$.
#warn[
形式矩阵不一定是 $PP^(r times s)$ 的矩阵,除非 $V$ 是定义在 $PP^n$ 上的线性空间.也就是说,不能直接套用矩阵的运算法则来计算.
但在使用时,我们可以取线性空间下的一组标准基,并将向量表示为在该标准基下的坐标形式,此时就可以对形式矩阵做矩阵操作了.
]
#def[定理1]设数域 $PP$ 上的线性空间 $V$ 中有两个向量组 (I) $alpha_1,alpha_2,dots.c,alpha_r$ 和 (II) $beta_1,beta_2,dots.c,beta_s$.如果向量组 (I) 可被向量组 (II) 线性表示且 $r>s$,那么向量组 (I) 必线性相关.
#prof[
#def[证明]由已知存在 $M_(s times r)$ 使得 $display(mat(alpha_1, alpha_2, dots.c, alpha_r) = mat(beta_1, beta_2, beta_s) bold(M)_(s times r))$.考虑:
$
theta = k_1 alpha_1 + k_2 alpha_2 + dots.c + k_r alpha_r
= mat(alpha_1,alpha_2,dots.c,alpha_r) mat(k_1;k_2;dots.v;k_r)
= mat(beta_1,beta_2,dots.c,beta_s) bold(M)_(s times r) mat(k_1;k_2;dots.v;k_r)
$
其中 $r(bold(M)_(s times r)) <= min(s,r) = s<r$,所以
]
#def[定理2]设数域 $PP$ 上的线性空间 $V$ 中有两个向量组 (I) $alpha_1,alpha_2,dots.c,alpha_r$ 和 (II) $beta_1,beta_2,dots.c,beta_s$.如果向量组 (I) 可被向量组 (II) 线性表示且向量组 (I) 线性无关,那么 $r<=s$.
#prof[即上一个命题的逆否命题.]
=== 向量组的等价
在数域 $PP$ 中,如果两个向量组能互相线性表示,则称这两个向量组等价.
#def[定理]两个等价的,线性无关的且含有有限向量个数的两个向量组,所含向量个数相等.
#def[性质]向量组的等价具有自反性、对称性、传递性.
=== 向量组的极大线性无关组
对于给定向量组的一个部分组,如果其线性无关且添加任意一个原向量组的向量都会变得线性相关.那么这个不分组是原向量组的一个极大线性无关组.
#def[性质1]任意一个有限向量个数的向量组,一定含有一个极大线性向量组.且向量组与它的极大线性向量组等价.
#def[性质2]一个向量组的任意两个极大线性向量组必等价且所含向量个数相等.
=== 向量组的秩
一个向量组的极大线性无关组的向量个数称为这个向量组的秩.
#def[性质1]秩为 $r$ 的向量组中.任意 $r+1$ 个向量必线性相关;任意 $r$ 个线性无关的向量都是原向量组的一个极大线性无关组.
#def[性质2]任意一个有限秩的向量组的线性无关的部分组,一定可以扩充成原向量组的一个极大线性无关组.
|
|
https://github.com/fredguth/typst-business-model-canvas | https://raw.githubusercontent.com/fredguth/typst-business-model-canvas/main/example/main.typ | typst | #import "../biz_canvas.typ": canvas
#show: _ => canvas(
title: [
= Modelo de Negócios
],
business: [
Biz
],
problems:[
== Problemas
#v(1em)
- problem 1
- problem 2
],
activities:[
== Atividades
#v(1em)
- activity 1
- activity 2
],
metrics:[
== Métricas
#v(1em)
- metric 1
- metric 2
],
proposition:[
== Proposta de Valor
#v(1em)
"proposition"
#v(2em)
=== Elevator Pitch
],
unfair:[
== Vantagem Imbatível
#v(1em)
- vantagem 1
],
channels:[
== Canais
#v(1em)
- channel 1
- channel 2
],
clients:[
== Clientes
#v(1em)
- segment 1
- segment 2
],
costs:[
== Custos
#v(1em)
- cost 1
- cost 2
] ,
revenues:[
== Receitas
#v(1em)
- revenue 1
- revenue 2
],
)
|
|
https://github.com/mrcinv/nummat-typst | https://raw.githubusercontent.com/mrcinv/nummat-typst/master/admonitions.typ | typst | #let admonition(title: none, color: none, content) = align(center,
box(
width: 98%,
align(left,
stack(
dir: ttb,
rect(width: 100%, fill: color, stroke: 0.3pt, title),
rect(width: 100%, fill: color.desaturate(80%), stroke: 0.3pt, content),
)
)
)
)
#let admtitle(type, title) = emph[#smallcaps(type) #h(1em) #title]
#let opomba(naslov: none, content) = admonition(
title: emph(naslov),
color: lime.desaturate(40%),
content,
) |
|
https://github.com/mps9506/quarto-lapreprint | https://raw.githubusercontent.com/mps9506/quarto-lapreprint/main/README.md | markdown | MIT License | # quarto-lapreprint Format

This is a typst template for quarto users. The original typst template is from [LaPreprint](https://github.com/LaPreprint/typst)[^distribution] and has been slightly modified for use in quarto.
[^distribution]: This is a modified redistribution of the original LaPreprint](https://github.com/LaPreprint/typst) Typst template created by <NAME> and distributed under the MIT license.

## Installing
```bash
quarto use template mps9506/quarto-lapreprint
```
This will install the format extension and create an example qmd file
that you can use as a starting place for your document.
## Using
The yaml header in [template.qmd](template.qmd) provides example starting points.
### Logos and branding
The theme of the document can be set to a specific color, which changes the headers and links. The default `theme` is blue. Change to red (or purple) using:
```yaml
theme: "`red.darken(50%)`{=typst}"
```
You can also supply a logo, which is either an image file location or content, allowing you to add additional information about the journal or lab-group to the top-right of the document. You can also set the `mainfont` which must be the name of a locally installed font.
```yaml
logo: my-logo.png
theme: "`red.darken(50%)`{=typst}"
mainfont: "Fira Sans"
```
## Title and Subtitle
You can have both a title and a subtitle:
```yaml
title: Pixels and their Neighbours
subtitle: A Tutorial on Finite Volume
```
### Authors and Affiliations
You can add both author and affiliations lists, each author should have a `name`, and can optionally add `orcid`, `email`, and `affiliations`. The affiliations are just content that is put in superscript, e.g. `"1,2"`, have corresponding identifiers in the top level `affiliations` list, which requires both an `id` and a `name`. If you wish to include any additional information in the affiliation (e.g. an address, department, etc.), it is content and can have whatever you want in it.
```yaml
authors:
- name: <NAME>
orcid: 0000-0002-7859-8394
email: <EMAIL>
affiliations: 1,2,🖂
- name: <NAME>
orcid: 0000-0002-1551-5926
affiliations: 1
- name: <NAME>
orcid: 0000-0002-4327-2124
affiliations: 1
institute:
- id: 1
name: University of British Columbia
- id: 2
name: Curvenote Inc.
```
For other information that you wish to affiliate with a specific author, you can use the `affiliations` field with any identifier you like (e.g. `†` or `🖂`) and then use the margin content or affiliations fields on the preprint to explain what it means.
### Abstract and keywords
You can include one or more abstracts as well as keywords. For a simple `abstract` the default title used is "Abstract" and you can include it with:
```yaml
abstract: |
Whatever content you want to include. You should be able to use *markdown* as well.
keyword: [Finite Volume, Tutorial, Reproducible Research]
```
### Margin content
The content on the first page is customizable. The first content is the `kind`, for example, "Original Research", "Review Article", "Retrospective" etc. And then the `pub-date`, which is by default the date you compiled the document if not specified. Note that currently you must use the Typst `datetime` format[^date].
[^date]: I'd prefer to use raw strings here, but I'm confused about how Quarto handles dates and how to pass them to Typst which has its own builtin date handling functions. So this is subject to change.
```yaml
kind: "Notebook Tutorial"
pub-date: "`datetime(year: 2023, month: 08, day: 21)`{=typst}"
```
You can also set `pub-date` to be a dictionary or list of dictionaries with `title` and `date` as the two required keys. The first date will be bolded as well as used in the document metadata and auto `short-citation`.
```yaml
kind: "Notebook Tutorial"
pub-date:
- title: Published
date: "`datetime(year: 2023, month: 08, day: 21)`{=typst}"
- title: Accepted
date: "`datetime(year: 2022, month: 12, day: 10)`{=typst}"
- title: "Submitted"
date: "`datetime(year: 2022, month: 12, day: 10)`{=typst}"
```
### Headers and Footers
You can control the headers and footer by providing the following information:
```yaml
open-access: true # not implemented yet
doi: 10.1190/tle35080703.1
venue: "`[ar#text(fill: red.darken(20%))[X]iv]`{=typst}"
short-title: Finite Volume Tutorial
short-citation: auto #not implemented yet
```
The first page will show an open-access statement and the `doi` if available. For DOIs, only include the actual identifier, not the URL portions:
Subsequent pages will show the `short-title` and `short-citation`. If the citation is `auto` (the default) it will be created in APA formatting using the paper authors.
The footers show the `venue` (e.g. the journal or preprint repository) the `date` (which is by default `today()`) as well as the page count.
### Incomplete
### Margins
The rest of the margin content can be set with `margin` property, which takes a `title` and `content`.
```yaml
margin-content:
- title: Key Points
content: |
* key point 1 is *important*.
* key point 2 is also important.
* this is the third idea.
- title: Corresponding Author
content: 🖂 [<EMAIL>](mailto:<EMAIL>)
- title: Data Statement
content: Associated notebooks are available on [GitHub]("https://github.com/simpeg/tle-finitevolume") and can be run online with [MyBinder]("http://mybinder.org/repo/simpeg/tle-finitevolume").
- title: Funding
content: Funding was provided by the Vanier Award to each of Cockett and Heagy.
- title: Competing Interests
content: The authors declare no competing interests.
```
You can use the margin property for things like funding, data availability statements, explicit correspondence requests, key points, conflict of interest statements, etc.
### Bibliography
typst handles the bibliography. `bibliography` points to the .bib file and `biblio-style` specifies the styling[^biblio]. Available styles are documented by Typst: https://typst.app/docs/reference/model/bibliography/. In text references and cross references should be written as specified in pandoc/Quarto: (https://quarto.org/docs/authoring/footnotes-and-citations.html#sec-citations).
[^biblio]: This might change in the future to using (or providing the option of) pandoc's builtin citeproc.
```yaml
bibliography: main.bib
biblio-style: apa
``` |
https://github.com/ShizhongP/easy-py | https://raw.githubusercontent.com/ShizhongP/easy-py/main/main.typ | typst | #import "@preview/ilm:1.2.1": *
#show outline: set text(font: "Source Han Serif", weight: "thin", size: 10pt)
#show outline: set par(leading: 10pt)
#show: ilm.with(
title: [
#text("福州大学超算团队\nAI 方向\n学习手册", size: 0.7em, font: "Source Han Serif") \ \
#text("I. python 入门", size: 1.3em, font: "Source Han Serif")
],
author: "",
date: datetime(year: 2024, month: 9, day: 6),
abstract: [
],
figure-index: (enabled: true),
table-index: (enabled: true),
listing-index: (enabled: true)
)
#set heading(numbering: "I.1.")
#show heading: it => [
#if (it.level == 1) {
set align(center)
set text(1em, weight: "regular")
block(smallcaps(it), height: 12pt)
} else {
set text(1em, weight: "regular")
block(smallcaps(it), height: 12pt)
}
#h(1em)
#v(-1em)
]
#set text(lang: "cn",font: "Source Han Serif", weight: "thin", size: 10pt)
#set par(leading: 1em, first-line-indent:1em)
#let fisrt-line-indent = it => {
it;"";v(-1.25em)
}
#show enum: fisrt-line-indent
#show link: it => { underline(it.body) }
#show emph: it => { text(blue,it.body) }
#set list(marker: (text("\u{00BB}", weight: "bold", baseline: -1pt)))
#let codes(fontsize: 10pt, body) = {
set text(size: fontsize)
[
#line(length: 100%, stroke: 0.5pt)
#body
#line(length: 100%, stroke: 0.5pt)
]
}
#let task(fontsize: 10pt, title, body) = {
set text(size: fontsize)
box(fill: rgb(10, 150, 255, 20), width: 100%, radius: 4pt)[
#pad(10pt)[
#text(size: 10pt, weight: "bold")[#title] \
#h(1em) #body
]
]
}
#let attention(fontsize: 10pt, title, body) = {
set text(size: fontsize)
box(fill: rgb(255, 00, 0, 15), width: 100%, radius: 4pt)[
#pad(10pt)[
#text(size: 11pt, weight: "bold", fill: rgb(255, 000, 0, 255))[#title] \
#h(1em) #body
]
]
}
#let suggestion(fontsize: 10pt, title, body) = {
set text(size: fontsize)
box(fill: rgb(0, 255, 200, 15), width: 100%, radius: 4pt)[
#pad(10pt)[
#text(size: 11pt, weight: "bold", fill: rgb(0, 150, 100,255))[#title] \
#h(1em) #body
]
]
}
#align(center, text(17pt)[
*前言*
])
编写这本学习手册的目的在于,让没什么编程经验的小白也能比较好的入门。我们尝试用比较通俗的方式向大家介绍编程中的一些重要概念和思想,这些都是从我们自身的学习过程中得到的经验和思考,当然也会因为水平有限,有些地方写的并不“通俗”,如果你有任何建议,请向我们反馈🙏。
在手册中,你会看到下面三种模块,与正文密切相关,请不要忽略
#task("任务")[
该模块中内容是一些需要大家完成的任务,用于巩固所学
]
#attention("注意")[
该模块的内容是一些注意事项,如果你觉得看不懂正文或者遇到解决不了的问题,可以参考这部分内容
]
#suggestion("建议")[
该模块的内容是一些建议,包括思考的方式,工具的推荐,都是我们宝贵的经验
]
本文的一些连接是CSDN的网站教程,并不说明CSDN是最佳的选择,但考虑到刚入门可能大多数的教程都来源于CSDN,同时考虑网络的原因,我们给出了一些这样的教程连接,如果有可能,请使用更优质的网站
下面开始学习吧🚀
#pagebreak()
= Python 简介
== 开发环境配置
=== python安装
到 #link("https://www.python.org/downloads/windows/")[官方网站] 下载
根据你的系统选择对应版本的 Python 解释器 (Windows,Linux,Macos),推荐 python 版本为 3.9 以上。具体安装过程可以参考 #link("https://blog.csdn.net/thefg/article/details/128601410")[Python安装教程]
#attention("注意事项")[
- 在项目中,绝大多数的路径都是英文字符的,常常会因为中文路径而产生一些未知的问题,因此建议之后安装的软件统一使用全英文的路径。
- 若使用的系统是Windows,建议下载路径不要选择C盘(若只有C盘或者C盘空间足够大可以忽略)。原因在于C盘是默认的系统盘,里面存储的大部分文件是系统所需,若C盘空间不足,一定程度上会影响体验。
]
在 Python 安装完成后,在你所选择的安装目录下,就会有 ``` python.exe``` 文件,点击即可运行python执行器,然后通过键盘输入`1+1`,按下回车之后,可以看到对应的计算结果为`2`。上面的例子就是一个非常简单的程序了,但是这样的方式是极其不便的,只能完成一些简单的程序。后面我们会介绍通过在代码编辑器中编写程序,以文件的形式运行程序的方法。
=== 环境变量
什么是环境变量?请先在Python的安装目录下打开*终端*
#suggestion("建议")[
- 当你不知道怎么做的时候,就要去网上搜寻相关的资料了,我们并不总会告诉你该如何做,必要的时候,要自行去搜索相关的资料完成相应的操作,通过这样的方式来不断提高解决问题的能力。
- 搜索引擎的选择: Edge浏览器自带的Bing, Chrome的google(需科学上网)
- 在提问之前,记住原则:1. STFW、2. RTFSC、3. RTFM (Search the friendly web, Read the friendly source code, read the friendly manuel)
]
在当前目录打开终端后,你会发现终端同样也是一个*交互式界面*, 通过键盘输入`./python.exe`,同样可以运行python执行器。上面的操作中,`./`代表的是在当前目录,而`./python.exe`则代表在当前目录下执行`python.exe`这个*可执行文件*。
如果我们希望在任何目录下,通过键入`pyhon.exe`即可执行python解释器呢?即不通过指定执行器所在的目录的方式就可以运行,这个时候就需要我们去配置*环境变量*了。环境变量的作用之一就是:告诉操作系统你的可执行文件的路径。具体配置Python环境变量的方法参考 #link("https://blog.csdn.net/weixin_45765073/article/details/125090676")[Win11中Python环境变量配置教程]
=== 编辑器
推荐使用 *VS Code* 作为代码编辑器,到 #link("https://code.visualstudio.com/download")[VS Code官网] 下载安装包。 Vs code 是一个强大的编辑器,可定制化性较高,插件系统非常完备,更多的玩法,自行探索。具体安装可以参考 #link("https://blog.csdn.net/thefg/article/details/131752996")[VS code安装教程]
== 编写你的第一个程序
在 Visual Studio Code 中,*项目的单位是文件夹*,即工作区。在工作区中有多个文件,通过点击文件可以在编辑窗口中编辑文件。
#task("新建项目")[
-------------------------------------------------------------------------------------------------------------------------------
- 创建新文件夹
- 使用 VSCode 打开该文件夹
- *在该文件夹下创建 main.py 文件*
- 在你的main.py文件中,输入`print("hello world!")`,然后保存
]
在 VSCode 中可以用使用快捷键 ``` ctrl + ~``` 唤出终端,在终端键入`python main.py`,回车之后,你的第一个程序就运行起来了!那么你能理解这段代码的含义吗?`print`就是一个在终端打印输出的*函数*,至于什么是函数,会慢慢讲到的。
到这里,开发环境已经准备好了。接下来我们来介绍Python的基础语法和代码结构
#pagebreak()
= Python 基础语法
== 数据类型、变量与基本运算
=== Python数据类型
程序离不开数据。把数字、字母和文字输入到计算机,就是希望它利用这些数据完成某些任务。接下里我们就来介绍在Python中常用的数据类型。
==== 整数
整数,就是没有小数的数据类型,这和数学上的整数概念是一致的。在 Python 中,整数的范围理论上是无限的,我们称之为*高精度*。Python 3 通过其内置的`int` 类型,支持任意精度的整数,这意味着你可以表示和处理非常大的整数,唯一的限制是可用的内存和计算资源。
#codes[
```python
a = 1234567890123456789012345678901234567890
b = 9876543210987654321098765432109876543210
result = a + b
print(result)
```
]
#task("试着运行一下看看")[
将上面的代码复制下来运行一下
]
从结果上来看,无论数字多大,Python 都能够正确处理。这与 C 语言不同,后者通常有固定的整数范围,例如 `int` 或 `long` 类型。
对于很大的数,例如`10000000000`,很难清楚0的个数。Python允许我们使用`_`对整型进行分隔。写成`10_000_000_000`和`10000000000`是完全一样的。
==== 浮点数
浮点数也就是小数,之所以称为浮点数,是因为按照科学记数法表示时,一个浮点数的小数点位置是可变的。比如,$1.20 times 10^9$和$12.0 times 10^8$是完全相等的。以下是关于Python浮点数的重要特点。
1. *浮点数表示*
- 对于很大或者很小的浮点数,必须使用科学计数法表示,*把10用e替代*,比如$1.2 times 10^9$和`1.2e9`等价。
- 浮点数能表示的范围是从 `1.7e-308` 到 `1.7e+308`,但精度有限,一般为 15-17 位有效数字。
#codes[
```python
large_num = 1.23e5 # 1.23 * 10^5,输出 123000.0
small_num = 1.23e-5 # 1.23 * 10^-5,输出 0.0000123
```
]
2. *浮点数精度*
浮点数的精度有限,因此在处理非常大或非常小的数时,可能会出现舍入误差。例如:
#codes[
```python
x = 0.1 + 0.2
y = 1.7e+308
print(x)
print(2*y)
# 输出 0.30000000000000004
# 输出 inf
```
]
#task("试着运行一下看看")[
尝试运行上述代码,观察输出的结果是否与你预想中的不太一样
]
由于浮点数的二进制表示限制,无法精确表示某些小数,这种误差通常在科学计算中很常见。可能你不太理解这方面的内容,目前我们不需要过分深入,在未来学习C语言内存管理时,会深入讨论关于二进制、内存管理方面的知识。
#suggestion("int 和 float")[
你可能会疑惑,既然有了`float`,为什么需要`int`类型呢?在运算上完全可以用`float`替代`int`,事实上`float`和`int`在计算机中的存储的方式并不一样(虽然都是二进制),有些功能必须由`int`来完成
]
==== 字符串
Python 的字符串是用于表示文本的数据类型。它是不可变的序列类型,这意味着一旦创建,字符串的值就不能修改。
字符串可以用单引号`'`、双引号`"`、三引号`'''` 或 `"""`来定义:
1. *字符串的定义*
#codes[
```python
# 单引号
str1 = 'Hello'
# 双引号
str2 = "World"
# 三引号(可用于定义多行字符串)
str3 = '''This is
a multiline
string'''
```
]
注意,`''`和`""`只是一种表达方式,并不作为字符串的一部分。所以`"Hello"`只有`H`,`e`,`l`,`l`,`o`这5个字符。如果`'`本身也是一个字符的话,那就可以使用`""`,比如`"I'm Superman"`。
2. *转义字符*
如果字符串内部既包含`'`又包含`"`怎么办?可以用转义字符`\`来标识,比如:
#codes[
```python
x = 'I\'m \"Superman\"!'
print(x)
#输出:I'm "Superman"!
```
]
#task("动手试试")[
转义字符`\`可以转义很多字符,比如`\n`表示换行,`\t`表示制表符,字符`\`本身也要转义,所以`\\`表示的字符就是`\`。\
大家请自己尝试创建几个字符串去print()看看结果。
]
如果字符串里面有很多字符都需要转义,就需要加很多`\`,为了简化,Python还允许用`r''`表示`''`内部的字符串默认不转义。比较一下下列的输出:
#codes[
```python
print('\\\t\\')
print(r'\\\t\\')
```
]
#attention("关于字符串")[
字符串的操作贯穿了Python的学习,在此只是简单的介绍字符串类型,在后续的章节会详细介绍字符串的相关操作。
]
==== 布尔值
在 Python 中,布尔(Boolean)是一种表示逻辑值的数据类型,主要用于控制程序的流程和判断逻辑。布尔类型只有两个值:`True` 和 `False`,分别代表逻辑上的“真”和“假”。
1. 布尔类型的表示
布尔值在 Python 中由关键字 `True` 和 `False` 表示(注意大小写)。布尔值是 bool 类型的实例。
#codes[
```python
a = True
b = False
```
]
2. 布尔运算
- 与运算(`and`):只有当两个操作数都为 `True` 时,结果才为 `True`。
#codes[
```python
True and True # 结果是 True
True and False # 结果是 False
```
]
- 或运算(`or`):只要有一个操作数为 `True`,结果就是 `True`。
#codes[
```python
True or False # 结果是 True
False or False # 结果是 False
```
]
- 非运算(`not`):取反运算,将 `True` 变为 `False`,将 `False` 变为 `True`。
#codes[
```python
not True # 结果是 False
not False # 结果是 True
```
]
3. 比较运算符
比较运算符用于比较两个值的大小或相等性,结果为布尔类型。
- 等于(`==`):判断两个值是否相等。
- 不等于(`!=`):判断两个值是否不相等。
- 大于(`>`)、小于(`<`)、大于等于(`>=`)、小于等于(`<=`):
#codes[
```python
5 == 5 # 结果是 True
5 == 6 # 结果是 False
5 != 6 # 结果是 True
5 != 5 # 结果是 False
5 > 3 # 结果是 True
3 < 2 # 结果是 False
4 >= 4 # 结果是 True
3 <= 1 # 结果是 False
```
]
==== 空值
空值是Python里一个特殊的值,用`None`表示。`None`不能理解为`0`,因为`0`是有意义的,而`None`是一个特殊的空值。
此外,Python还提供了列表、字典等多种数据类型,还允许创建自定义数据类型,我们后面会继续讲到。
=== 变量
在Python中,变量是用于存储数据的容器。也就是装数据的瓶子,变量在Python中不需要声明其类型,Python是一种*动态类型语言*,因此可以自动推断变量的类型(整数、浮点数、字符串等等)。
1. *变量的命名*
- 变量名必须以字母(a-z 或 A-Z)或下划线 `_` 开头,后面可以跟字母、数字或下划线。
- 变量名是区分大小写的(`myVar` 和 `myvar` 是两个不同的变量)。
- 变量名不能是Python的保留关键字(如 `if`, `else`, `for` 等)。
#codes[
```python
# 正确的命名
my_variable = 10
_myVar = "Hello"
# 错误的命名会抛出 SyntaxError 错误
3myvar = 15
```
]
#attention("变量的正确命名是一件大事")[
正确且恰当的变量命名可以让工程结构更加清晰化,为编程便利提供帮助。当变量增多时,多使用下划线`_`为变量完整命名。变量的命名规范可参考 #link("https://chendy.tech/CS1501_CyPhy-gh-pages/advanced/chap1_order/variableName.html")[变量命名规范]
]
2. *变量的赋值*
在Python中,变量通过赋值语句(=)将值赋给变量,并且允许在一行代码中同时为多个变量赋值。
#codes[
```python
x = 5
y = "Hello, World!"
x, y, z = 1, 2, "Python" #多变量赋值
```
]
#task("尝试一下")[
你可以自己动手测试一下,x、y、z内储存的内容。
]
可以创建变量当然也意味着可以删除。使用`del`关键字可以删除变量。
#codes[
```python
x = 10
del x # 变量 x 被删除
```
]
3. *变量的类型*
Python中每个变量都有一个类型,你可以使用 type() 函数来查看变量的类型。
#codes[
```python
x = 10 # int
y = 3.14 # float
z = "Python" # str
is_true = True # bool
print(type(x)) # <class 'int'>
```
]
由于Python是动态类型语言,变量的类型可以在运行时更改。例如:
#codes[
```python
x = 10 # x 是整数类型
x = "Hello" # x 现在变成字符串类型
```
]
4. *全局变量和局部变量*
在函数中定义的变量是局部变量,只在函数内部可见。如果需要在函数外部访问变量,可以使用 `global` 关键字定义全局变量。这方面内容不需要现在了解,在后续函数的章节会着重介绍。
5. *常量*
虽然Python没有原生的常量(值不会改变的变量),但是通常使用全大写字母命名变量来表示它是常量,比如:
#codes[
```python
PI = 3.14159
```
]
#task("小测试")[
理解变量在计算机内存中的表示也非常重要。当我们写
#codes[
```python
a = 'QWE'
```
]
Python的解释器做了两件事:
1. 在内存中创建了一个`'ABC'`的字符串;
2. 在内存中创建了一个名为`a`的变量,并把它指向`'ABC'`。
也可以把一个变量`a`赋值给另一个变量`b`,这个操作实际上是把变量`b`指向变量`a`所指向的数据。
#codes[
```python
a = 'QWE'
b = a
a = 'ABC'
print(b)
```
]
*最后一行打印出变量b的内容到底是`'ABC'`呢还是`'XYZ'`?* Try it!!!!!!!
]
=== 基本运算及其优先级
Python提供了多种基本运算,包括算术运算、比较运算、逻辑运算等。了解这些运算符及其优先级对编写正确的程序非常重要。以下是Python中的基本运算符及其优先级规则。
1. *算术运算符*
Python支持常见的算术运算:
#table(
columns: (0.25fr,0.25fr,0.25fr),
align: center,
[*运算符*],[*描述*],[*示例*],
[`+`],[加法],[`3 + 2`=5],
[`-`],[减法],[`3 - 2`=1],
[`*`],[乘法],[`3 * 2`=6],
[`/`],[除法],[`3 / 2`=1.5],
[`//`],[整除],[`3 // 2`=1],
[`%`],[取余],[`3 % 2`=1],
[`**`],[幂运算],[`3 ** 2`=9],
)
#codes[
```python
a = 10
b = 3
print(a + b) # 输出 13
print(a - b) # 输出 7
print(a * b) # 输出 30
print(a / b) # 输出 3.3333...
print(a // b) # 输出 3
print(a % b) # 输出 1
print(a ** b) # 输出 1000
```
]
#task("动手尝试")[
动手尝试一下Python的算术运算
]
2. *比较运算符*
比较运算符用于比较两个值,并返回布尔值(`True` 或 `False`):
#table(
columns: (0.25fr,0.25fr,0.25fr),
align: center,
[*运算符*],[*描述*],[*示例*],
[`==`],[等于],[`3 == 3`=True],
[`!=`],[不等于],[`3 != 2`=True],
[`>`],[大于],[`3 > 2`=True],
[`<`],[小于],[`2 < 3`=True],
[`>=`],[大于等于],[`3 >= 2`=True],
[`<=`],[小于等于],[`2 <= 3`=True],
)
#codes[
```python
a = 10
b = 5
print(a > b) # 输出 True
print(a == b) # 输出 False
```
]
3. *逻辑运算符*
#table(
columns: (0.25fr,0.25fr,0.25fr),
align: center,
[*运算符*],[*描述*],[*示例*],
[`and`],[与],[`True and False` = False],
[`or`],[或],[`True and False` = True],
[`not`],[非],[`not False` = True],
)
#codes[
```python
a = True
b = False
print(a and b) # 输出 False
print(a or b) # 输出 True
print(not a) # 输出 False
```
]
4. *赋值运算符*
Python的赋值运算符用于将值赋给变量,可以与算术运算符结合使用。
#table(
columns: (0.25fr,0.25fr,0.25fr),
align: center,
[*运算符*],[*描述*],[*示例*],
[`=`],[赋值],[`x = 5`],
[`+=`],[加法赋值],[`x += 5`等同于`x = x + 5`],
[`-=`],[减法赋值],[`x -= 5`等同于`x = x - 5`],
[`*=`],[乘法赋值],[`x *= 5`等同于`x = x * 5`],
[`/=`],[除法赋值],[`x /= 5`等同于`x = x / 5`],
[`//=`],[整除赋值],[`x //= 5`等同于`x = x // 5`],
[`%=`],[取余赋值],[`x %= 5`等同于`x = x % 5`],
[`**=`],[幂赋值],[`x **= 5`等同于`x = x ** 5`],
)
#codes[
```python
x = 10
x += 5 # x 现在是 15
x *= 2 # x 现在是 30
```
]
5. *位运算符*
位运算符用于对整数进行二进制操作。如果你现在还不是很了解什么是二进制,可以先去理解一下二进制。
#table(
columns: (0.25fr,0.25fr,0.25fr),
align: center,
[*运算符*],[*描述*],[*示例*],
[`&`],[按位与],[`3 & 2` = 2],
[`|`],[按位或],[`3 | 2` = 3],
[`^`],[按位异或],[`3 ^ 2` = 1],
[`~`],[按位取反],[`~3` = -4],
[`<<`],[按位异或],[`3 << 1` = 6],
[`>>`],[按位异或],[`3 >> 1` = 1],
)
#codes[
```python
a = 3 # 011
b = 2 # 010
print(a & b) # 输出 2,二进制为 010
```
]
6. *运算优先级*
在数学当中,我们都知道乘法和除法要先算,后算加减,在编程语言中,同样存在这样的运算规则,这样子先算某一种运算符再算下一种运算符暗喻着不同种运算符存在一种优先顺序,我们称之为*优先级*。Python运算符的优先级决定了运算的顺序。优先级从高到低如下:
- 指数运算符:`**`
- 按位取反:`~`
- 乘法、除法、整除、取余:`*`, `/`, `//`, `%`
- 加法、减法:`+`, `-`
- 位移运算:`<<`, `>>`
- 按位与:`&`
- 按位异或:`^`
- 按位或:`|`
- 比较运算:`<`, `<=`, `>`, `>=`, `!=`, `==`
- 逻辑非:`not`
- 逻辑与:`and`
- 逻辑或:`or`
- 赋值运算:`=, +=, -=, *=, /=, %=, **=, //=, &=, |=, ^=, >>=, <<=`
如果想改变默认的运算顺序,可以使用括号 () 提高优先级:
#codes[
```python
result = (2 + 3) * 4 # 结果是 20,因为括号内的加法先计算
```
]
== 分支
计算机在面对不同场景的时候一样也有自己的判断,这也是为什么它能完成许多自动化任务的原因。这章节我们就来了解一下,如何为计算机植入能做出判断的“大脑”。
1. *if语句*
比如,我们要判断一个数字是否大于5,我们就可以使用if进行判断。
#codes[
```python
x = int(input("请输入你要验证的数字"))
if x > 5:
print("x is greater than 5")
```
]
#suggestion("解释")[
if相关的判断语句常与布尔类型的值挂钩,当`x > 5`的条件为真时,才执行`print("x is greater than 5")`。
]
#attention("关于I/O")[
什么是I/O?简单来说就是计算机的输入与输出。在Python中分别对应input()和print(),input()用来接受来自你的输入,而print()则是将你指定的内容打印到屏幕上。
]
#attention("关于缩进")[
我们观察到在使用 `if`条件后需要`:`,并且在`print()`前需要缩进(通常使用四个空格)。 与许多其他编程语言不同,Python不使用花括号 `{}` 来定义代码块,而是依赖缩进来表示代码的层次结构。Python非常依赖缩进来确定代码的逻辑结构,错误的缩进会导致 `IndentationError` 错误。
]
2. *else语句*
在上面的例子中,我们处理`x > 5`的情况。现在,我想对剩下的情况也进行一个输出,我们该怎么做呢?这就需要用到`else`语句了。
#codes[
```python
x = int(input("请输入你要验证的数字"))
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
```
]
3. elif
`elif`是"else if"的缩写。在学习数学区间的时候,我们并不是只把一个进行简单的一刀切划分成两个区间。面对多个区间的分支,我们就需要使用到`elif`语句。就用我们用年龄划分为例:
#codes[
```python
age = 15
if age >= 18:
print("你已经成年了")
elif age >= 12:
print("你是青少年")
else:
print("你是小孩子")
```
]
当`age`是15时,第一个`if`条件为假,但`elif`条件为真,因此执行`"你是青少年"`的打印语句。
#task("if语句执行的特点")[
`if`语句执行有个特点,它是从上往下判断,如果在某个判断上是`True`,把该判断对应的语句执行后,就忽略掉剩下的`elif`和`else`。\
所以你可以解释一下为什么下面程序打印的是“你是青少年”吗?
#codes[
```python
age = 20
if age >= 6:
print('你是青少年')
elif age >= 18:
print('你是成年人')
else:
print('你还是个孩子')
```
]
]
3. *单行条件表达式(三目运算符)*
这是什么东西?简单来说,我们只需要对区间进行一刀切分成两个区间时,再去用代码块的形式会显得代码很冗余且不够简洁。Python允许使用单行的条件表达式(也叫三元表达式)来简化代码:
#codes[
```python
age = 20
message = "成年人" if age >= 18 else "未成年人"
print(message)
```
]
#task("任务")[
- 使用三元表达式实现:两个数取较大数
]
== 循环
循环,意思就是不断的重复做一件事。现在让我们来计算一道数学题`1+2+3+4`把它交给计算机,这很简单。那如果是`1+2+3+...+10000`呢?直接把它交给计算机怕是不可能了。为了能让计算机得到这么庞大的表达式,我们就需要使用循环。
1. *for循环*
for 循环通常用于遍历序列(如列表、元组、字符串、字典或集合)。它会在序列的每个元素上循环一次。
#codes[
```python
for i in range(5):
print(i)
#输出将是从 0 到 4 的数字。
```
]
`range()` 函数是 Python 中常用来生成数值序列的函数,常与 `for` 循环一起使用。\
#task("动手尝试一下")[
你可以在自己的计算机上体验一下range()函数的魅力🤩,并完成计算1-100整数之和。
#codes[
```python
sum = 0
for x in [...] :
sum += x
print(sum)
```
]
请在[...]处填入相关代码。
]
#attention("关于序列")[
序列的相关知识点已经出现在第三章数据结构中,在这里先感受一下循环的魅力
#codes[
```python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
```
]
for循环可以遍历序列内的内容并对他们进行操作
]
2. *while循环*
`while`循环,作为循环的一种,但是不如for来的灵活且常用。
#codes[
```python
count = 0
while count < 5:
print(count)
count += 1
```
]
`count += 1`作为控制循环结束的条件,如果没有这段代码,`while`循环将不会停止。
3. *控制循环的语句*
`continue`:
试想一下,当我们对一组数据进行打印的时候出现了一个我们不想要打印的数字,我们该如何避免它呢?那我们肯定想要跳过它!
#codes[
```python
for i in range(5):
if i == 3:
continue
print(i)
```
]
`continue`为我们提供了这个需求,它可以帮我们跳过当前的迭代,继续下一次的迭代。也就是说当我们遇到`3`的时候,我们不会去执行`print()`。输出为 `0,1,2,4`。
`break`: 同样的,当一组数据打印到某个地方,我们就想要它停止打印。
#codes[
```python
for i in range(5):
if i == 3:
break
print(i)
```
]
`break`为我们提供了打断的需求。输出为 `0,1,2`,因为在 `i` 等于 `3` 时,break 终止了循环。·
`else`子句:`for` 和 `while` 循环可以带有 `else` 子句。当循环正常结束时,`else` 子句的代码会被执行;如果循环被 `break` 终止,`else` 代码块则不会被执行。
#codes[
```python
for i in range(5):
print(i)
else:
print("循环正常结束")
```
]
输出为 `0,1,2,3,4 `以及 "`循环正常结束`"。
#suggestion("再议input()!")[
分支和循环的知识点结束,皆大欢喜👏 但是在这里我还是想再说一说input()这个函数。在前面我们使用到input()的例子中,我们还使用了int()。这是为什么呢?大家可以试试把int()删除,看看会出现什么错误!
在这里我也不给大家卖什么关子,input()返回的数据类型是`str`,也就是说无论你输入的是什么数字还是字母,计算机都会自动把它认为是字符串类型。所以我们要使用int()这个内置的函数,将`str`类型转化为`int`。这样整数才能和整数进行比较对吧!
]
== 过程抽象
*过程抽象*(Procedural Abstraction)是编程中的一种设计思想,它指的是将一系列具体的操作步骤或实现细节隐藏在一个过程、函数或方法的背后。简单来说,我们只需要了解这个过程的输入和输出,而不需要关心其具体实现。
=== 函数
现在我们来定义一个函数$f(x) = x + 1$ ,意思是输入一个数,得到的输出比输入大1。我们可以多次使用它来得到输出,并且在条件允许的情况下对它进行修改。所以学习函数的重点在于提高代码的复用性和可维护性。
1. *调用函数*
Python内置了很多有用的函数,我们可以直接调用。比如`print()`和`input()`也是属于函数的类型,我们可以多次调用它们。
#attention("Python文档")[
要调用一个函数,需要知道函数的名称和参数。如print()函数,print是函数名,()内输入的内容是函数的参数。一般的函数都不仅仅只有一个参数,具体可以通过Python官方文档查阅#link("Python官方文档查阅")[https://docs.python.org/3/library/functions.html]
]
2. *定义函数*
在Python中,定义一个函数要使用`def`语句,依次写出`函数名`、`括号`、`括号中的参数`和冒号`:`,然后,在缩进块中编写函数体,函数的返回值用return语句返回。
#codes[
```python
def greet(name):
print(f"Hello, {name}!")
print("How are you?")
greet("Alice")
# 输出:
# Hello, Alice!
# How are you?
```
]
正如你所看到的那样,`greet` 函数封装了打印问候信息的过程。使用者只需调用 `greet`,而不必关心 `print` 的具体实现。
如果你只是想要先定义一个函数,但不具体实现它的功能。可以定义一个空函数:
#codes[
```python
def nop():
pass
```
]
缺少了`pass`,代码运行就会有语法错误。
2. *函数参数与返回值*
- 函数的参数允许我们根据不同的输入,灵活执行相同的操作,从而避免重复代码。参数在函数定义时指定,调用时传入实际值。
- 函数可以返回结果,也可以不返回值。返回值通过 `return` 语句实现,调用者可以获取和使用这些返回的结果。
#codes[
```python
def add_and_sub(a, b):
return a + b, a - b
a, b = add(3, 5)
print(a)
print(b)
# 输出: 8
# -2
```
]
在这个例子中,`add_and_sub` 函数接收两个参数 `a` 和 `b`,并返回它们的和与差。调用者可以获得这个返回值并进行进一步处理。
#attention("关于两个位置的a,b")[
在函数内的`a`,`b`为函数的形式参数,函数外的`a`,`b`为程序的变量。两者并无实质性的关联,互不冲突。如果不想做到混淆可以取其他更有辨别性的变量名,如`add_result`和`sub_result`。
]
#task("来交作业")[
编写一个函数来判断一个数是否为质数(素数)\
*题目描述*:质数是大于1的自然数,且除了1和它本身以外,没有其他因数。你需要编写一个函数 is_prime(n) 来判断传入的整数 n 是否为质数,并返回布尔值 True 或 False。\
*函数定义*:
#codes[
```python
def is_prime(n):
pass
```
]
*要求*:
1. 输入一个正整数 n,并判断 n 是否为质数。
2. 如果 n 是质数,返回 True;否则返回 False。
3. 你需要在函数中使用循环和条件语句来检查 n 是否有其他因数。
*输入输出示例*:
#codes[
```python
print(is_prime(7)) # 输出: True
print(is_prime(10)) # 输出: False
print(is_prime(2)) # 输出: True
print(is_prime(1)) # 输出: False
```
]
]
3. *默认参数与可选参数*
Python函数支持为参数提供默认值,这使得某些参数在调用函数时可以省略。如果省略了参数,函数会使用定义时指定的默认值。
#codes[
```python
def greet(name, message="Hello"):
print(f"{message}, {name}!")
greet("Alice") # 输出: Hello, Alice!
greet("Bob", "Welcome") # 输出: Welcome, Bob!
```
]
在这里,`message` 是一个可选参数,它有一个默认值 ``"Hello"``,如果在调用时不传入 `message` 参数,默认值会被使用。
4. *可变数量的参数*
Python支持传递可变数量的参数,使用 `*args` 表示任意数量的非关键字参数,`**kwargs` 表示任意数量的关键字参数。
#codes[
```python
def sum_numbers(*args):
return sum(args)
result = sum_numbers(1, 2, 3, 4)
print(result) # 输出: 10
```
]
== 数据抽象
*数据抽象* (Data Abstraction)数据抽象的核心思想是将“是什么”(What)与“怎么做”(How)分开。通过数据抽象,开发者只需要关心数据的使用方式,而不需要了解数据的内部实现细节。例如,在面向对象编程(OOP)中,数据抽象的一个常见例子是“类”。类定义了对象的属性(数据)和方法(行为),但隐藏了具体的实现细节。
=== 类与对象
类是Python实现数据抽象的主要工具。通过定义类,可以将数据(属性)和操作数据的方法(函数)封装在一起。在类的外部,用户无需了解类的内部实现,只需调用类提供的接口来操作数据。换句话说,类主要定义对象的结构,然后我们以类为模板创建对象。
==== 使用类
在python一切皆为对象,对象是类的实例。要使用类我们就要先对其进行实例化。这里我们使用python内置的List类进行演示。
#codes[
```python
l = list((3, 1, 2)) #实例化list类,并生成对象l
print(l) #输出对象l内的数据
#输出 [3, 1, 2]
l.sort() #这是List类的内置函数,对l内的元素进行排序
print(l)
#输出 [1, 2, 3]
```
]
从这个例子中我们可以看到List类的使用方法,它包含了数据和操作数据的方法。通过这样一个数据抽象的过程我们能更方便地处理问题。当然除了List, 在python中还有Set, Dict, Tuple等数据类型,后面我们会更加详细的介绍它们。
#suggestion("int和float")[
int和float与数据抽象密切相关。尽管在Python中我们通常将它们视为基本数据类型,但它们实际上是类,而这些类在设计中也运用了数据抽象的原则。
int和float类提供了一组明确的接口(方法),通过这些接口,用户可以对这些对象进行各种操作,而不需要了解其背后的实现。例如:
#codes[
```python
a = 5
b = 2
# 你可以执行以下操作而不需要知道具体如何实现
print(a + b) # 相加
print(a.__add__(b)) # int 类的内置加法方法,实际上相加操作就是由这个函数实现的
```
]
]
==== 创建类
当python内置的类已经不满足你的需求了,你就可以自己进行数据抽象,创建一个类。下面是一个简单例子:
#codes[
```python
class Dog:
def __init__(self): #初始化函数
self.Race = 'dog'
def call(self): #方法
print('wang')
a = Dog()
a.call() #输出wang
print(a.Race) #输出dog
```
]
在这个例子中我们创建了一个狗的实例,它包含了最基础的数据Race,还有方法call。`__init__`为一个特殊的方法,它会在类实例化时自动执行,也就是说在a被创建时,这个方法就自动执行了。`self`通常用来指代现在的对象,它的存在使对象可以使用类中定义的方法和对象的数据。
下面我们来进一步优化一下该类,给狗加一个名字,并加一个`play` 的方法:
#codes[
```python
class Dog:
def __init__(self, name):
self.Race = 'dog'
self.name = name
def call(self):
print('wang')
def play(self):
self.call()
print(f'{self.name}欢快的打滚')
a = Dog('张致选') #实例化
a.play() #输出 wang 张致选欢快的打滚
```
]
这个例子中`__init__`处多加了一个参数name,我们要在实例化时就输入该参数,因为`__init__`方法在实例化时就执行了。在赋值给`self.name`后我们就能在`play()`中使用它。(没有赋值将不能在别的函数中访问,这也是`self`的作用所在),同样在类的方法中我们也能互相调用,同样是通过`self. `的方式引用。
类的使用还有更加复杂的方法,在后面的面对对象程序设计中,我们还会介绍更多的细节,包括继承和多态等,现在主要是要了解数据抽象的思想:把生活中复杂的物体抽象出来,对其进行封装成各种数据和方法,并方便我们的操作。
#task("来交作业")[
抽象一个简单的图书馆\
*题目描述*:建立一个图书馆类,存放历史,哲学,教育书籍。并能够统计整个图书馆的数据,能列出三种图书的数量,增加图书的数量\
*类的定义(参数未给全)*:
#codes[
```python
class Library:
def __init__(self,):
pass
def total(self,):
pass
def list_book_num(self,):
pass
def add_book(self,):
pass
```
]
*要求*:
1. 要求包扩数据:`history`,`philosophy`, `educate`,分别表示历史,哲学,教育图书的数量。
2. 要求建立方法:`total`计算整个图书馆图书数量并返回,`list_book_num`列出每种图书的个数并返回字符,`add_book`能够增加这几种书的数量。
*输入输出示例*:
#codes[
```python
A = Library(100, 50, 60)
print(A.total())
A.add_book('his', 100)
A.add_book('edu', 20)
print(A.list_book_num())
A.add_book('math', 200)
# 输出
# 170
# History:200
# Philosophy:50
# Educate:80
# There is no such book
```
]
]
#pagebreak()
= 数据结构与标准库
== 数据结构与 ADT
*数据结构*是指在计算机中存储和组织数据的方式。它是具体的实现,通常包括数据的存储格式和操作方法。
思考一个问题,为什么我需要数据结构呢?如果从实际生活中看,想象一下你的房间里有很多东西,如果把所有东西都放在一个大箱子里,找东西时就会很麻烦。相反,如果你把书放在书架上,把衣服放在衣柜里,那么每次找东西就会方便多了。数据结构就是这样的“收纳方式”,帮助我们更高效地存储和访问数据。那么从计算机的角度来看,如果给你若干个数字,你会采取怎样的方式进行存储呢?学过变量之后,你可能这样想:
#codes[
给定n个数,假定n=3
```python
a = 第一个数
b = 第二个数
c = 第三个数
```
]
但这样的方式极其不优雅,并且当n取值到很大的数时,我们也不可能手动去创建n个变量!因此是否能只使用一个变量去存储n个数,并且保证我们能快速访问到这任意n个数呢?回想一下,高中我们是否有使用一个符号代表一堆数的例子呢?自然地,我们使用 $RR$ 表示自然数集合,我们使用一个符号表示某个集合,如$a = {1,2,3}$,当然我们这里要讲的不是集合,在计算机世界里面,集合有其特殊性质,在这里我们只是希望找到一种简单存储数的方式。事实上,我们可以采用一种叫做*数组(array)*的数据结构去存储n个数,形式如下:
#codes[
给定n个数
```python
array = [第一个数,第二个数, ... , 第n个数]
```
我们可以通过*下标*的方式去访问这n个数
```python
array[0] == 第一个数
array[1] == 第二个数
...
array[n-1] == 第n个数
```
]
#attention("从 ' 0 ' 开始的计算机世界")[
在计算机世界中,绝大数的数据结构的下标都是从`0`开始的,这样设置的原因在于计算机系统底层都是使用二进制存储,二进制中只有`0`,`1`两种数字,因此当你向访问数组中第1个数字的时候,是使用`array[0]`的形式访问。当然如果你觉得别扭,我们以后统一从第`0`个数开始,`array[0]`就是第`0`个数
]
通过上面数组这样的形式,理论上,给定任意n个数,都能够存储并且都能够快速访问。但事实上Python并没有提供叫做数组的数据结构,而是提供了一个叫做*列表*的数据结构*List*(当然也是数组的一种,但是肯定是有特殊之处的)。如果要细分下来的话,数据结构有非常多,下面我们就依次介绍Python中的四大基本数据结构*List*,*Tuple*,*Dict*,*Set*。
== List
在 Python 中,`list` 是一种内置的数据结构,用于存储有序的元素集合。列表可以包含不同类型的元素,包括数字、字符串、甚至其他列表。以下是关于 Python 列表的一些常用操作:
1. *创建列表*
可以使用方括号 `[]` 创建一个列表,也可以使用 `list()` 函数。
#codes[
```python
# 使用方括号创建列表
my_list = [1, 2, 3, 'apple', 'banana']
# 使用 list() 函数创建列表
another_list = list((4, 5, 6)) # 从元组创建列表
```
]
#task("试着创建一个列表")[
- 创建一个my_list列表
- 对列表元素进行*遍历*并打印
```python
for i in my_list:
print(i)
```
]
#attention("注意")[
不同于c语言和c++,python中List中的元素可以是任意类型,并没有规定同一个列表只能有一种类型,它可以包含任意的数据类型,float,int,字符串等。当然在很久很久很久以后,出于可读性和安全的考虑,我们同样可通过某种声明来限定列表中的元素类型,其实是*类型标注*
]
2. *访问元素*
列表的元素通过下标(索引)访问,索引从 0 开始。若从尾部开始则下标从`-1`开始
#codes[
```python
first_element = my_list[0] # 访问第一个元素,结果为 1
last_element = my_list[-1] # 访问最后一个元素,结果为 'banana'
```
]
#task("通过下标的方式访问列表元素")[
- 通过下标的方式循环遍历列表元素
```python
for i in range(len(my_list)):
print(my_list[i])
```
- 通过下标的方式逆序访问列表元素
```python
for i in range(-1,-len(my_list),-1):
print(my_list[i])
```
]
3. *修改元素*
可以通过下标(索引)修改列表中的元素。
#codes[
```python
my_list[1] = 'orange' # 将第二个元素修改为 'orange'
```
]
#task("试着反转列表中的元素")[
如果列表元素为[1,2,3],则反转后的列表元素应该为[3,2,1]
```python
for i in range(len(my_list)//2):
tmp = my_list[i]
my_list[i] =
my_list[-(i+1)] = tmp
```
]
4. *添加元素*:
- `append()`: 在列表末尾添加单个元素。
- `extend()`: 在列表末尾批量添加元素。
- `insert()`: 在指定位置插入元素。
#codes[
```python
my_list.append('grape') # 在末尾添加 'grape'
my_list.extend([1,2,3]) # 在末尾添加1,2,3
my_list.insert(1, 'kiwi') # 在索引 1 处插入 'kiwi'
```
]
5. *删除元素*:
- `remove()`: 删除指定值的第一个匹配项。
- `pop()`: 删除指定索引的元素,默认删除最后一个元素。
#codes[
```python
my_list.remove('apple') # 删除 'apple'
last_item = my_list.pop() # 删除最后一个元素并返回
```
]
6. *查找元素*:
- `index()`: 返回指定值的索引(如果不存在会引发异常)。
#codes[
```python
index_of_banana = my_list.index('banana')
```
]
7. *列表切片*
可以使用切片操作符 `:` 获取列表的子集。用法为 `list[起始下标:结束下标:步长]`,和`range`函数一样,左闭右开,默认步长为`1`。
#codes[
```python
sub_list = my_list[1:3] # 获取索引 1 到 2 的元素
sub_list2 = my_list[-3:] # 获取最后 3 个元素
sub_list3 = my_list[-3:-1] # 获取倒数第三到倒数第二的元素
sub_list4 = my_list[::-1] # 列表的逆序
sub_list5 = my_list[4:1:-1] # 索引 1 到 3 的元素的逆序
```
]
#task("尝试不同的切片方式")[
我们看到了列表切片当中有三个可变参数,`起始下标`,`结束下标`,`步长`,上面我们已经给出了几种方式,动动你的手试一下吧
]
8. *列表推导式*
Python 提供了一种简洁的方式来生成列表,称为列表推导式。这是一个语法上非常简洁的实现,当然你完全可以使用循环+分支的形式替代列表推导式,但是这样就代码就变得不那么`优雅`
#codes[
```python
squares = [x**2 for x in range(10)] # 生成 0 到 9 的平方数列表
filter_squares = [x for x in squares if x%2==0] # 只保留suqares中 2 的倍数
```
]
#task("写点推导式吧")[
给定列表
```python
my_list = list(range(21))
```
1. 使用列表推导式过滤掉列表中3的倍数的数
2. 使用列表推倒式将列表中所有数加2
]
#suggestion("增删改查")[
我们可以看到List的操作有增加,删除,修改,查找元素(*增删改查*)这四种操作,事实上,绝大多数的数据结构的基本操作也都是增删改查,包括之后的 Tuple,Dict,Set同样也是如此。所以当你学习某一个数据结构时,不知道从何入手,可以先关注这四个基本功能是如何实现的,再去关注不同数据结构之间的特性和差异,根据经验,按照这样的方式去理解和记忆,效率是比较高的。
]
== Tuple
在 Python 中,`tuple`(元组)是一种内置的数据结构,用于存储有序的元素集合。与列表相比,元组是不可变的,这意味着一旦创建,元组中的元素就*不能被修改*。以下是关于 Python 元组的一些关键点:
1. *创建元组*
可以使用圆括号 `()` 创建元组,也可以使用 `tuple()` 函数。
#codes[
```python
# 使用圆括号创建元组
my_tuple = (1, 2, 3, 'apple', 'banana')
# 使用 tuple() 函数创建元组
another_tuple = tuple((4, 5, 6)) # 从元组或其他可迭代对象创建
```
]
2. *访问元素*
元组的元素通过索引访问,索引从 0 开始。
#codes[
```python
first_element = my_tuple[0] # 访问第一个元素,结果为 1
last_element = my_tuple[-1] # 访问最后一个元素,结果为 'banana'
```
]
3. #strike[*修改元素*]*不可变性*:
修改元素?不,我们刚才讲了元组一旦创建,其元素无法更改,你不能添加、删除或修改元组中的元素,不然会报错,自己体验一下
#codes[
```python
# 尝试修改元素会引发错误
# my_tuple[1] = 'orange' # TypeError: 'tuple' object does not support item assignment
```
]
4. *元组推导式*
Python 不支持元组推导式,但可以通过生成器表达式和 `tuple()` 函数创建元组。
#codes[
```python
squared_tuple = tuple(x**2 for x in range(5)) # 结果: (0, 1, 4, 9, 16)
```
]
#task("思考,动手")[
你可能会觉得元组好像没什么用?不能增加也不能修改元素,甚至连删除都做不到,跟列表功能那么丰富的数据结构没法比。但是既然存在就有其道理,其不变性正是我们需要的,因为在某些场景当中,我们要求数据必须是不可变,否则就会产生问题!
- 为了避免过于枯燥,下面你动手创建一个元组,并尝试修改元素内容
```python
my_tuple = (1,2,3)
my_tuple[0] = 1
```
- 试着将两个元组相加会产生什么结果呢?试着运行以下代码看看输出结果
```python
my_tuple = (1,2)
my_tuple2 = (3,4)
print(my_tuple+my_tuple2)
```
- 将元组乘上一个数字会发生什么呢?
```python
my_tuple = (1,2,3)
print(my_tuple * 3)
```
- 其实List也支持相加和乘数的操作,你同样也可以去尝试下
]
== Dict
字典,这个名词大家应该很熟悉了,计算机世界里面的字典和现实世界中的字典在功能上很相似。现实中,字典的一个字对应一块解释内容,计算机中,一个`键`对应一个`值`。
在 Python 中,`dict`(字典)是一种内置的数据结构,用于存储键值对。字典是无序的、可变的,并且可以使用不可变的类型(如字符串、数字、元组)作为键。以下是关于 Python 字典的一些关键点:
1. *创建字典*
可以使用花括号 `{}` 或 `dict()` 函数创建字典。
#codes[
```python
# 使用花括号创建字典
my_dict = {
'name': 'Alice',
'age': 30,
'city': 'New York'
}
# 使用 dict() 函数创建字典
another_dict = dict(name='Bob', age=25, city='Los Angeles')
```
]
2. *增加元素*
直接通过新的键赋值来添加。
#codes[
```python
my_dict['email'] = '<EMAIL>'
```
]
3.*删除元素*
可以使用 `del` 语句或 `pop()` 方法
#codes[
```python
# 删除元素
del my_dict['city'] # 使用 del
age = my_dict.pop('age') # 使用 pop() 返回被删除的值
```
]
4. *访问和修改元素*
可以通过键访问字典中的值,并且可以直接修改值。
#codes[
```python
# 访问元素
name = my_dict['name'] # 结果: 'Alice'
# 修改元素
my_dict['age'] = 31 # 将年龄修改为 31
```
]
5. *常用方法*
- `keys()`: 返回字典中所有键的视图。
- `values()`: 返回字典中所有值的视图。
- `items()`: 返回字典中所有键值对的视图。
#codes[
```python
keys = my_dict.keys() # 获取所有键
values = my_dict.values() # 获取所有值
items = my_dict.items() # 获取所有键值对
```
]
#task("试着遍历下")[
看下输出结果,你就知道这些函数到底是干什么用的了
```python
for key in my_dict.keys():
print(key)
print("====================")
for value in my_dict.values():
print(value)
print("====================")
for item in my_dict.items():
print(item)
```
]
6. *字典推导式*
Python 支持字典推导式,使得创建字典更加简洁。
#codes[
```python
squared_dict = {x: x**2 for x in range(5)} # 结果: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
```
]
#task("写点代码")[
使用字典统计列表中的每个元素出现的次数
如my_list = [1,1,2,2,3] 则my_dict={1:2,2:2,3:1}
- 提示:你可以使用`in`来判断某个元素是否在字典当中
]
== Set
这里的集合和数学上的集合可以认为是等价。在 Python 中,`set`(集合)是一种内置的数据结构,用于存储唯一的、无序的元素集合。集合提供了高效的成员测试和集合运算。以下是关于 Python 集合的一些关键点:
1. *创建集合*
可以使用花括号 `{}` 或 `set()` 函数创建集合。
#codes[
```python
# 使用花括号创建集合
my_set = {1, 2, 3, 'apple', 'banana'}
# 使用 set() 函数创建集合
another_set = set([4, 5, 6]) # 从列表创建集合
```
]
2. *集合特性*
- *无序性*: 集合中的元素是无序的,因此不能通过索引访问。
- *唯一性*: 集合中的元素必须是唯一的,如果重复添加,集合会自动去重。也就是集合元素不能重复
#codes[
```python
duplicate_set = {1, 2, 2, 3}
# 结果: {1, 2, 3}
```
]
3. *访问集合元素*
由于集合是无序的,不能通过索引访问,但可以使用 `in` 关键字检查某个元素是否存在。
#codes[
```python
if 'apple' in my_set:
print("苹果在集合中")
```
]
4. *集合操作*
- *添加元素*: 使用 `add()` 方法添加单个元素。
#codes[
```python
my_set.add('orange') # 添加 'orange' 到集合
```
]
- *删除元素*: 使用 `remove()` 或 `discard()` 方法删除元素。
#codes[
```python
my_set.remove('banana') # 删除 'banana',如果不存在则抛出异常
my_set.discard('grape') # 删除 'grape',如果不存在则不抛出异常
```
]
- *清空集合*: 使用 `clear()` 方法清空集合。
#codes[
```python
my_set.clear() # 清空集合
```
]
5. *集合运算*
集合支持多种运算,包括并集、交集、差集和对称差集。这些集合运算和数学上的集合是一致的,并不想做过多解释,请STFW自行了解下吧
- *并集*: 使用 `union()` 或 `|` 运算符。
#codes[
```python
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2 # 结果: {1, 2, 3, 4, 5}
```
]
- *交集*: 使用 `intersection()` 或 `&` 运算符。
#codes[
```python
intersection_set = set1 & set2
# 结果: {3}
```
]
- *差集*: 使用 `difference()` 或 `-` 运算符。
#codes[
```python
difference_set = set1 - set2
# 结果: {1, 2} 集合1有的元素而集合2没有的元素
```
]
- *对称差集*: 使用 `symmetric_difference()` 或 `^` 运算符。
#codes[
```python
symmetric_difference_set = set1 ^ set2
# 结果: {1, 2, 4, 5} 两个差集的并集
```
]
6. *集合推导式*
Python 支持集合推导式,可以快速创建集合。
#codes[
```python
squared_set = {x**2 for x in range(5)}
# 结果: {0, 1, 4, 9, 16}
```
]
#task("写点代码")[
这一部分内容确实无趣,但是确实是需要经历的过程,有时候很难保证学习的过程是有趣的。因此来写点代码吧🌞
- 给定两个*列表*,求两个列表的共同元素
]
#suggestion("关于数据结构")[
到这里我们就介绍完了python中基本的数据结构,还有更多复杂的数据结构我们么有介绍,可能在很久以后我们会特别出一个章节来讲数据结构。其实其它编程语言大抵上也会提供类似List,Dict,Set这样的数据结构,掌握好每种数据结构的特点和基本的*增删改查*,学习其他编程语言的门槛也就不会那么高了。
]
== Algorithms
介绍完数据结构,现在我们来介绍下一些基本算法。*算法*可以通俗地理解为解决问题的“步骤说明”或“食谱”。就像做饭时需要按照食谱的步骤来准备和烹饪食材,算法则是告诉我们如何通过一系列明确的步骤来完成某项任务或解决某个问题。
1. *明确性*:每一步都必须清楚明了,不能有任何模糊的地方。就像食谱中的每个步骤都要具体,比如“切洋葱”而不是“处理洋葱”。
2. *有序性*:步骤需要按照特定的顺序进行。有些步骤是前置的,必须在后续步骤之前完成。比如在煮汤之前,必须先把食材准备好。
3. *有限性*:算法应该在有限的步骤内完成,也就是说,当你按照步骤执行后,最终会得到一个结果,而不是无限循环。
4. *输入与输出*:算法通常会接收输入(如食材),经过处理后产生输出(如熟食)。输入可以是任何形式的数据,而输出是最终结果。
举个例子:假设你要把一堆数字从小到大排序。这个问题的算法可能包括以下步骤:
#codes[
1. 从头到尾查看每个数字。
2. 找到当前未排序部分中最小的数字。
3. 把这个最小的数字放到已排序部分的末尾。
4. 重复步骤1到3,直到所有数字都排序完成。
]
在这个例子中,你可以看到每一步都是明确的(算法步骤),经过有限次的循环后结束程序(有限性),并且有一个清晰的开始和结束(结束点是这堆数据已经有序),输入是一堆数字,而输出是这堆数字的有序排列(输入与输出)。简而言之,算法就是解决问题的步骤和方法,可以用于计算、数据处理、搜索、排序等多个方面。掌握算法的思维方式有助于我们更有效地解决各种问题。
#suggestion("建议")[
在解释某个名词的过程,我们希望能有一些专业性的解释,难免会有一些类似八股文的内容,不是要求大家死记硬背,而是理解性的记忆,并且尽可能思考其中提出这样理论的动机。就比如当你拿到一份代码的时候,你能够快速分析,得到程序的输入输出,以及每一步算法大概的作用,能够从你的理解出发而系统性地解释一份代码,这些需要一点系统和理论的指导,当然如果你觉得这是没有必要的过程,可以跳过,这种能力是需要通过阅读大量代码才能慢慢培养而成的。
]
上面介绍的例子其实就是选择排序的算法过程,为了便于理解,此处再举几个例子:
- 当我们要求两个数之和时, 其中的`加法`就是一个算法
- 如果我们要求1-100的数字之和,那么这个问题的解法也是一个算法
- 如果我们要求一堆数中的最大数,那么求出这个最大数的过程是一个算法
现在你可以理解“算法是解决问题的方法或过程”这句话的含义了吧。接着我们介绍python中内置的一些基本算法
=== 排序
什么是排序呢?排序就是将无序的序列变成有序的,对于数字来讲,有从小到大的排序,有从大到小的排序。
前面我们已经提到了一个*选择排序*的例子,那么你能够根据算法原理而给出代码实现呢?下面是选择排序的一种实现方式
#codes[
```python
def selection_sort(arr):
n = len(arr)
for i in range(n):
# 假设当前索引 i 是最小值的索引
min_index = i
# 在未排序部分寻找最小值
for j in range(i + 1, n):
if arr[j] < arr[min_index]:
min_index = j
# 交换找到的最小值和当前索引 i 的值
arr[i], arr[min_index] = arr[min_index], arr[i]
return arr
my_list = [64, 25, 12, 22, 11]
sorted_list = selection_sort(my_list)
print("排序后的列表:", sorted_list) # 输出: [11, 12, 22, 25, 64]
```
]
#suggestion("看不懂代码?")[
看不懂是正常的,我们并没有特别详细地讲解选择排序的原理,因为本手册的重点并不在于教大家算法,那这个时候怎么办呢?STFW
]
当然如果每次需要数进行排序,都要写一遍这样的函数多麻烦,其实Python中内置了`sorted()` 函数可以对*可迭代对象*进行排序,其内部实现是一种叫做`Timsort`的排序算法,感兴趣可以自行去了解下。下面是`sorted`函数的使用案例
#codes[
```python
# 对列表进行排序
my_list = [5, 2, 9, 1, 5, 6]
sorted_list = sorted(my_list) # 默认升序,reverse=False
print(sorted_list) # 输出: [1, 2, 5, 5, 6, 9]
# 使用 reverse 参数进行降序排序
sorted_list_desc = sorted(my_list, reverse=True)
print(sorted_list_desc) # 输出: [9, 6, 5, 5, 2, 1]
```
]
#attention("可迭代对象")[
简单的理解就是,内部的元素是有序的数据结构,你可以遍历里面的元素
*遍历*就是挨个访问数据结构内的元素
]
=== 查找最大值和最小值
使用内置的 `max()` 和 `min()` 函数可以快速找到可迭代对象中的最大值和最小值。
#codes[
```python
# 查找最大值和最小值
max_value = max(my_list) # 结果: 9
min_value = min(my_list) # 结果: 1
```
]
#task("试着实现下")[
- 不用max函数,你能否实现从一个列表中找出最大值呢?下面这是一种简单实现呢?
```python
def max_num(my_list):
max_n = my_list[0]
for num in my_list:
if(num > max_n):
max_n = num
return max_n
my_list = [342,234,564,23,456]
print(max_num(my_list))
```
- 那么实现从列表中找出最小值,你应该也会了吧?
- 现在我希望从列表中找出第二小的值,又该如何实现呢?动手尝试一下吧
]
=== 求和与平均值
可以使用 `sum()` 来计算总和,结合 `len()` 计算平均值。也可以直接使用`mean()`计算平均值
#codes[
```python
# 计算总和和平均值
total = sum(my_list) # 结果: 28
average = total / len(my_list) # 结果: 4.67
#直接计算平均值
average = mean(my_list)
```
]
=== 过滤和映射
使用 `filter()` 和 `map()` 函数可以对可迭代对象进行过滤和映射操作。
- `filter(func,iterable)`,第一个参数为函数,第二个参数为可迭代对象。通常我们喜欢使用`lambda`函数当作第一个参数,第二个参数可以是列表。功能是只保留可迭代对象中的满足func的元素。如果你觉得上面的表述太难懂了,可以跳过,关注于如何使用这个函数即可。
- `map(func,iterable)`,参数和`filter`是一样的,功能是对可迭代对象中的每个元素做变化,如做平方等。
#codes[
```python
# 过滤,只保留偶数
even_numbers = list(filter(lambda x: x % 2 == 0, my_list)) # 结果: [2, 6]
# 将每个元素平方
squared_numbers = list(map(lambda x: x ** 2, my_list)) # 结果: [25, 4, 81, 1, 25, 36]
```
]
#task("熟悉起来")[
给定一个列表,使用`filter`和`map`完成下列任务
- 过滤列表中类型不为int的元素
- 对列表中的每个元素取绝对值,可以使用`abs()`函数对数取绝对值
]
#attention("匿名函数和高阶函数")[
关于`lambda`,其实叫做*匿名函数*,而`filter`和`map`这样可以接受函数为参数的函数,我们称之为*高阶函数*。这些概念我们会在后面的函数式编程中为大家作解释。
]
=== 集合操作
事实上,集合操作也是一种算法,前面介绍集合的时候已经给出,这里不再赘述
=== 字符串操作
前面我们说到了字符串,在python中字符串的操作是比较灵活的,其实字符串具备和列表一样的切片功能
#codes[
```python
s = "hello,world!"
sub_s = s[0:5:1]
print(sub_s)
```
]
Python 也提供了丰富的字符串方法,如 `join()`、`split()`、`replace()` 等。
- `join(word)`,将可迭代对象(列表,元组等)`words`使用调用该函数的字符串拼接起来,返回一个字符串
- `split(word)`,以`word`为间隔符,将字符串分割开,返回一个列表
- `replace(word,new_word)`,将字符串中`word`全部替换成`new_word`,返回替换完的字符串
#codes[
```python
# 字符串连接
words = ['Hello', 'World','!']
sentence = ' '.join(words) # 结果: 'Hello World !'
# 字符串分割
split_sentence = sentence.split(‘ ’) # 结果: ['Hello', 'World' , '!']
# 替换字符串
new_sentence = sentence.replace('World', 'Python') # 结果: 'Hello Python !'
```
]
#task("试着实现这几种函数呢")[
- `join`的内部实现你是否能够大概`感知`到呢?下面是一种实现方式
```python
def join(seperator,words):
s = ""
for word in words[:-1]:
s = s + word + seperator
s += words[-1]
return s
seperator = ' '
words = ["hello","world","!"]
s = join(seperator,words)
print(s)
```
- 试着动手实现下`split`和`repalce`函数吧
]
#suggestion("数据结构与算法")[
关于数据结构与算法,我们在这里只是非常非常简单地介绍了一些数据结构与算法,如果你想了解更多,可以从 #link("https://www.hello-algo.com/")[hello algo!]看起,对大家之后的程序设计课有很大帮助,事实上,当系统学完该手册后,你也应该去学数据结构与算法了
]
到这里,我们的第三部分也结束了。接下来我们会介绍一些编程语言理论相关的知识,这些都是宝贵的编程思想。
== 模块
模块是 Python 中的一种代码组织方式,可以把相关的代码放在一个文件里,方便管理和重用。通俗地说,模块就像是一个工具箱,你可以把常用的工具(函数、类、变量等)放在里面,其他地方想用的时候只需要打开这个工具箱就可以了。
1. *代码分组*:
- 模块允许你将相关的功能放在一个文件中,比如把所有与数学计算相关的函数放在一个 `math_utils.py` 的文件中。
2. *重用性*:
- 一旦创建了模块,你可以在其他程序中导入它,避免重复编写相同的代码。
3. *命名空间*:
- 每个模块都有自己的命名空间,这意味着模块内部定义的变量和函数不会与其他模块的变量和函数冲突。
举个例子
想象你在做一个项目,需要一些常用的计算功能,比如加法、减法等。你可以创建一个模块
#codes[
`calculator.py`:
```python
# calculator.py
def add(x, y):
return x + y
def subtract(x, y):
return x - y
```
]
然后在你的主程序中,你可以使用`import`来导入这个模块,使用里面的函数:
#codes[
`main.py`:
```python
# main.py
import calculator
result1 = calculator.add(5, 3)
result2 = calculator.subtract(10, 4)
print(result1) # 输出: 8
print(result2) # 输出: 6
```
]
上面这个的例子的目录结构应该是
#codes[
```shell
- 项目文件夹
- main.py
- cauculator.py
```
]
Python中,有很多这样的*内置模块*,这些内置模块也成为*标准库*,利用这些已有的模块,不需要自己再去实现复杂的函数,就可以快速完成程序的编写。下面介绍一些常见的内置模块吧
=== math
主要提供一些数学运算的函数,直接看具体的例子吧,主要还是学会如何使用这些函数
#codes[
```python
import math # 导入math模块(库)
print(math.pi) # 圆周率
print(math.sqrt(4)) #开根号
print(math.log(2)) #对数函数
print(math.sin(2)) #三角函数
...
```
]
还有其他很多很多的函数在`math`模块里面,请自己去尝试一下吧。
=== time
时间模块,提供一些时间相关的函数
#codes[
```python
import time
# 获取当前时间戳
current_time = time.time()
print(current_time)
# 暂停执行 2 秒
time.sleep(2)
print("Waited for 2 seconds.")
```
]
#task("程序计时")[
- 使用`time`模块完成对某一个程序的运行时间计时
- 提示:用程序最后的时间点减去程序开始的时间点
]
=== datetime
日期模块,可以获取系统的日期,还有一些其他时间相关的函数
#codes[
```python
from datetime import datetime
# 获取当前日期和时间
now = datetime.now()
print(now)
# 格式化日期
print(now.strftime("%Y-%m-%d %H:%M:%S"))
```
]
=== random
随机库,使用一些随机函数,如取如取随机值,随机抽样等
#codes[
```python
import random
# 生成一个随机浮点数
print(random.random())
# 从列表中随机选择一个元素
fruits = ['apple', 'banana', 'cherry']
print(random.choice(fruits))
```
]
#task("随机取数字")[
- 请STFW如何使用random完成,在某一区间内取随机数
]
=== os
用于操作操作系统功能,如文件和目录操作。
#codes[
```python
import os
# 获取当前工作目录
print(os.getcwd())
# 列出当前目录下的文件
print(os.listdir('.'))
```
]
#suggestion("更多的模块")[
Python中还有很多内置模块,如json,csv,sqlite,request等,请自行STFW学习吧
当然你还可以下载*第三方模块*(就是需要下载和安装的),Python目前有丰富的第三方库,你可以通过`pip`安装,具体的请看*工具链*那一部分的包管理工具
]
#pagebreak()
= 编程范式入门
== 面向过程编程
面向过程编程(Procedural Programming)是一种编程范式,它将程序视为一系列按顺序执行的步骤或过程。这个范式强调通过过程(或函数)来组织代码,通常包括以下几个特点:
+ 模块化:程序被分解为多个小的、可重用的过程或函数,每个过程执行特定的任务。
+ 顺序执行:程序的执行是线性的,通常是从上到下逐行执行。
+ 变量和数据:通过使用变量来存储数据,并在过程之间传递数据。
+ 控制结构:使用控制结构(如条件语句和循环)来控制程序的执行流。
面向过程编程的核心是*过程(函数)*,使用方式设程序时,通常采用自顶向下的开发方式,先确定程序的最终输出,再通过将功能拆分为多个子功能,并逐级向下,直到将所有功能都拆分成比较原始函数为止
考虑一下这样的场景:需要设计一个简易通讯录,该通讯录具备,添加联系人,删除联系人,查看联系人的功能,你会怎样设计呢,事实上你很可能这样设计
#codes[
```python
def 添加联系人(联系人信息)
def 删除联系人(联系人信息)
def 查看联系人()
def 初始化通讯录()
```
]
我们将通讯录的功能拆分成几个函数去实现,分成几个模块完成对应的功能,事实上这几个功能函数可能还可以进行拆分,比如添加联系人这个操作,我们还可以设定一些判定操作,比如,判定输入的电话号码是否合法,给这个联系人添加头像等等之类更复杂和细的操作。就是通过这种功能模块过程的逐渐划分,最终我们可以得到一套设计方案,这就是所谓的面向过程。
== 面向对象编程
#attention("注意")[
- 前面我们已经讲述过数据抽象的内容了,如果你觉得你已经掌握了数据抽象,可以跳过这部分的引言,直接关注面向对象的三大特性。
- 本章的内容会有大量的知识点(一些基础的抽象思想),有些内容是需要反复理解,如果你觉得这个过程痛苦,不坊自己从现实的角度去考虑计算机世界里的这些抽象问题的必要性,我想说的是,我们只提供一个角度的思考和学习方式(能力和写作水平有限),你要有自己的思考和想法。学习本身应该是自由的
]
面向对象编程(OOP Oriented Object Programing)可以通俗地理解为一种编程方式,它把现实世界中的事物抽象成“对象”,并通过这些对象来组织和管理代码。那么什么是*对象*呢?想象一下,你在生活中看到的各种事物,比如“猫”、“汽车”。在编程中,这些事物就被称为对象。每个对象都有自己的特点(属性)和可以做的事情(方法)。比如,猫的属性可能是“颜色”和“年龄”,而它的方法(行为)可能是“猫叫”和“吃”。
为什么需要*对象*这个概念呢?试着想一下,如果要使用编程语言描述通讯录中的联系人呢,你会怎么做?首先我们肯定会想,一个联系人有姓名,电话,年龄,性别等,假设有一个人叫做张三,电话18800000000,年龄23,性别男,自然地可以像下面的代码这样描述
#codes[
```python
name = "张三"
age = 23
sex = "男"
tel = "18800000000"
```
]
但是这样的表示实在是不优雅呀,如果再来一个叫李四的人,你又得去手动创建4个变量来存储李四的信息。那么有没有办法简化这一过程呢?
既然张三,李四,在属性上形式都一样,只是具体的取值不同,此时我们就可以将其抽象成*类(class)*,*类*可以理解为一个类别,比如动物,植物是一种类别,通过类来创建对象。在Python中,我们可以使用关键字`class`来对某一个类别进行声明,具体的形式如下:
#codes[
```python
class Person:
name = 姓名
age = 年龄
sex = 性别
tel = 电话
```
]
那么既然已经将*人*这个类抽象出来了,如何通过这个类来创建对象呢?事实上,Python中的`class`都自带一个`__init__()`的函数(方法)(*即使你不去声明,它本身仍存在一个无参数的`__init__`方法*),用于提供初始化对象(如其函数名`initialize`),我们可以通过这个方法来初始化对象的一些信息,但是其实我们不用显式的调用它,而是像使用函数一样使用`类名(参数列表)`的方式去创建对象即可,具体实现如下:
#codes[
```python
class Person:
def __init__(self,name,age,sex,tel):
self.name = name
self.age = age
self.sex = sex
self.tel = tel
Person1 = Person("张三",23,"男","18800000000") #调用__init__函数创建一个对象
Person2 = Person("李四",18,"男","18810000000")
```
]
#attention("self")[
self其实就是对象本身,这么讲可能有点难懂。其实在调用`__init__`函数时,已经创建了一个对象,这个对象在类内就是`self`,然后通过`self.属性` 的方式对属性的进行初始化和赋值
```
调用 ############ 产生 赋值 ##########################
Person()-----> # __init__ # ----> self ----> # self.属性 = 传入的属性 #
############ ##########################
```
]
上面的过程讲述了如何使用Python的`class`声明类,和使用类来创建对象,那么创建了对象之后,如何访问对象对应的属性值呢?使用`.`就可以访问一个对象的属性了
#codes[
```python
print(Person1.name) # 张三
print(Person1.age) # 23
print(Person1.sex) # 男
print(Person1.tel) # 18800000000
```
]
要更改对象属性值也很简单,直接通过赋值的方式
#codes[
```python
Person1.age = 18
print(Person1.age) # 18
```
]
#task("动动手指")[
- 创建一个商品类,有商品名称,价格,生产地,商家
- 创建一个商品类对象
- 修改商品类对象的任意属性
]
前面提到了如何声明类和创建类对象,但这样就结束了吗?那这个结构也太简单了。事实上,一个"类别"总有某些特殊的行为,就像人会走路,吃饭,睡觉,鸟会飞,鱼会游一样,这些行为在类里面叫做*方法*。我们可以在类里定义函数,类里面的函数就是方法了,具体可以看下面几个例子
#codes[
```python
#人
class Person:
def __init__(self,name,age):
self.name = name
self.age = age
def eat():
pass
def sleep():
pass
#鸟
class Bird:
def __init__(self,age):
self.age = age
def fly():
print("flying")
```
]
我们同样可以使用`对象.方法`的形式使用类的方法
#codes[
```python
bird1 = Bird(18)
bird1.fly() # flying
```
]
#attention("__init__ ")[
为什么我说,即使不去声明`__init__`它本身也有一个`__init__`方法呢?事实上,我们可以认为在Python中所有*类型皆是对象*,而这些类都有一个共同祖先`Object`,`Object`具有`__init__`这个方法(无参数的),Python中所有类都会*继承*`Object`,因此具备`Object`这个类的所有属性和方法。至于什么是继承,请往下看
]
=== 面向对象三大特性
面向对象中有三大特性,分别是封装,继承,多态。接下来我们会举一些简单的例子帮助大家理解
==== 封装Encapsulation
想象一下这样的场景:如果你有一个银行账户,你肯定不希望你的账户信息能被随意访问或者篡改,因此我们必须约束外界对我们账务信息的访问。在面向对象中,这样的形式我们称之为封装。所谓*封装*,就是是把数据和操作这些数据的方法放在一起,并保护这些数据不被随意修改。就像一个黑盒子,你只能通过盒子外面的按钮来控制盒子内部的机制,而不能直接看到或改动里面的东西。这种机制能够保护对象的内部状态,防止外部代码直接访问和修改,从而提高了系统的安全性和可维护性。
以下是一个简单的 Python 示例,演示了封装的概念:
#codes[
```python
class BankAccount:
def __init__(self, balance=0):
self.__balance = balance # 私有属性,外部无法直接访问
def deposit(self, amount):
if amount > 0:
self.__balance += amount
print(f"Deposited: {amount}")
else:
print("Invalid deposit amount.")
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
print(f"Withdrawn: {amount}")
else:
print("Invalid withdraw amount.")
def get_balance(self):
return self.__balance # 提供公共方法访问私有属性
# 使用封装
account = BankAccount()
account.deposit(100) # 输出: Deposited: 100
account.withdraw(50) # 输出: Withdrawn: 50
print(account.get_balance()) # 输出: 50
```
]
我们来解释一下上面的代码:
首先我们定义了一个`BankAccount`类,为其设定一个*私有属性*`__balance`(什么是私有属性?请往后看看),外部代码无法直接访问。由于私有方法是不能直接通过外界访问的,因此我们还定义了`deposit`、`withdraw` 和 `get_balance` 这些公共方法,提供了对私有数据的安全访问和操作。
接着创建了一个`account`对象,使用`deposit`方法存100进 `account`的账户中,使用`withdraw`从`account`对象中取出50,通过`get_galance()`获取`account`对象中的账户余额。
通过这样的方式,我们封装了`BackAccount`的内部实现,外界程序不能直接修改和访问其私有程序,并且我们向外界提供了公共方法实现`BackAccount`的一些操作,当然这些操作外界也不知道具体是什么,只能接收到一个结果。这样子极大程度上保证了`BackAccount`的内部安全,同时只对外提供必要的接口(方法),也能简化程序的实现
#attention("私有属性和私有方法")[
私有属性是指那些不能被外部直接访问的属性。在Python中,在类中使用`__`开头的属性就是私有属性。那么具体是什么意思呢?看下面这个例子
#codes[
```python
class Person:
def __init__(name,tel):
self.name = name
self.__tel = tel
P = Person("张三","18800000000")
print(P.name)
print(P.__tel)
```
]
如果你运行上面这个代码你会发现`print(P.__tel)`这一行运行时会报错,原因在与`__tel`在`Person`类中是私有的,你不能在`Person`类外直接访问,只能在类内部使用,类的内部即为,声明类的整个过程,从`class`到缩进结束。
所谓的私有方法也是类似的,在Python中, 类中以`__`为开头的方法即为私有方法
#codes[
```python
class Person:
def __private():
printf("private")
def func(self):
self.__private()
P = Person()
P.func()
P.__private()
```
]
运行上面代码你会发现`P.__private()`这一行报错,因为`__private`是私有方法,但是你可以通过定义`func`函数的方式间接使用`__private`方法
]
#task("任务")[
- 为之前实现的商品类添加私有属性,销量,库存
- 为商品类添加私有方法:出售商品(想想出售一个商品的时候会发生什么行为呢?)
]
==== 继承Inheritance
想象一下这样的场景吧,如果你已经创建了*动物*这样的类别,它已经具备动物类里面的基本行为,奔跑,进食,睡眠等行为,假设你也已经实现了这样的方法。那么如果此时又需要你创建一个*狗*类呢?你是不是也要重新实现,奔跑,进食,睡眠的方法,如果这样的话,岂不是很麻烦,最好的方法是让*狗*类能直接拥有*动物*类的行为和属性,那要怎么实现呢?答案是使用*继承*。
所谓*继承*是一种让新类可以从已有类获取属性和方法的机制。允许一个类(子类)基于另一个类(父类)创建新类,从而实现代码的重用和扩展。通过继承,子类具备了父类的*所有的属性和方法*,并可以*重写*或*实现*这些方法,以满足特定需求。比如,`Animal`类可以是一个更一般的类,而`Cat`和`Dog`可以从`Animal`继承一些共同的特性。具体地可以看下面这个例子
#codes[
```python
class Animal:
def __init__(name,age):
self.name = name
self.age = age
def speak(self):
print("叫")
def run(self):
print("跑!")
# 声明狗类
class Dog(Animal):
def speak(self):
print("汪汪汪!🐕")
# 声明猫类
class Cat(Animal):
def speak(self):
print("喵喵喵!🐱")
```
]
我们来解释一下上面这段代码
首先我们声明了`Animal`这个`父类(基类)`,定义了`__init__`和`speak`方法,
然后我们声明了`Dog`类,继承了`Aniamal`的属性和方法`speak`和`run`,但是又重新声明了`speak`的实现,这种子类重新声明父类的方法形式我们称为*方法重写*,如果不对方法重写,那么子类调用方法时就是使用父类的方法,比如`run`
然后又声明了`Cat`类,类似于`Dog`重新声明了`speak`方法,但是可以看到实现的内容和`Dog`的`speak`是不同,这也正常嘛,因为🐈和🐕的叫声不同
子类对象可以调用父类已经实现的方法。我们可以创建一个实例`dog`,调用`run`,然后调用`speak`。
同样的可以创建`cat`
#codes[
```python
dog = Dog("小七",3)
dog.run() # 跑
dog.speak() # 汪汪汪
cat = Cat("小黑",2)
cat.run() # 跑
cat.speak() # 喵喵喵
```
]
#task("任务")[
- 新建一个狼类🐺,继承`Animal`,狼类有呼啸,奔跑等行为
- 在这样一个场景:在汽车城里,有很多种类的车,燃油车,电车🚗,甚至两轮电动车🛵。车具备的行为是行驶,但是消耗的燃料不一样。请你设计这几个类的实现把
]
==== 多态Polymorphism
多态允许不同类型的对象以相同的方式使用相同的方法。比如,不管是猫还是狗,它们都有一个“叫”的方法,但具体的叫声可能不同,也就是具体的函数内容是不同的。你可以用相同的方式调用它们的“叫”方法,这就是*多态*。多态有两种,分为运行时多态和编译时多态
1. *编译时多态(静态多态)*:
- 通过*方法重载*(同一类中定义多个同名但参数不同的方法)和*运算符重载*实现。
- 例如:在 Python 中,虽然不支持方法重载,但可以通过默认参数或可变参数实现类似效果。
具体是什么意思呢?看下面这个例子
#codes[
```python
class Animal:
def eat(self,food=" "):
print("吃"+food)
A = Animal()
A.eat() # 吃
A.eat("草") # 吃草
```
]
我们来解释一下上面这个代码
首先,我们定义了`Animal`这个类,声明了`eat`这个方法
接着我们创建了对象`A`,调用两次`eat`方法,两次传入不同的参数,产生了不同结果,这种在我们编写`eat`方法时就可以预见的不同结果的方式就是编译时多态,即根据函数内部实现就能推测出最后的几种执行结果。
#attention("方法重载")[
所谓方法重载就是,方法名相同,但是参数列表不同,如下面的两个方法,方法名相同,但参数的个数不同。
#codes[
```python
def add(a,b):
def add(a,b,c)
```
]
但是实际上,在Python中,不允许在同一个类中定义两个同名的方法,因此我们只能通过可变参数的方法,实现类似与方法重载的功能。
运算符号重载也是类似的,只不过是对`__add__`这中内置的运算符函数进行重载,具体的案例STFW吧
]
2. *运行时多态*
- 通过继承和*方法重写*(子类重写父类的方法)实现。这些我们前面提到过
- 具体调用哪个方法在运行时决定,这种多态性是面向对象程序设计中最常见的形式。
具体什么是运行时多态呢?请看下面这个例子,
#codes[
```python
class Animal:
def speak(self):
raise NotImplementedError("Subclasses must implement this method")
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
def make_animal_speak(animal):
print(animal.speak())
# 使用多态
dog = Dog()
cat = Cat()
make_animal_speak(dog) # 输出: Woof!
make_animal_speak(cat) # 输出: Meow!
```
]
我们来解释一下上面这段代码:
`Animal` 是一个*基类*,定义了一个*抽象方法* `speak()`,它的子类 `Dog` 和 `Cat` 实现了这个方法。
多态的实现:`make_animal_speak` 函数接受一个 `Animal` 类型的参数,并调用其 `speak()` 方法。根据传入对象的不同,具体调用的 `speak()` 方法也不同。
上面这样的形式就多态的一种体现,事实上在我们定义`make_animal_speak`时,我们根本不知道传入的参数`animal`是一个什么类型,只有在真正传入对象后,运行的过程才能确定其是`Dog`类还是`Cat`类,从而去调用相应类的方法。
#attention("抽象方法")[
*抽象类*,为何称其为抽象,原因在与抽象类不适合实例化(创建对象),就比如你说水杯是一个物品,苹果是一个物品,手机也是一个物品,如果你要使用*物品*这个类创建对象,你认为这是否合适呢?过于高度的抽象本身并不适合在程序中使用,但你可以通过子类继承抽象类的方式实现抽象类的方法,进而创建子类对象
在面向对象里,*抽象方法*通常是定义在抽象类里,一般来说,抽象类不能创建对象,因此也不能直接调用抽象方法,必须通过子类继承抽象类,子类重写抽象方法,调用子类的方法的形式来实现。具体的例子就是上面提到的`Dog`实现了父类`Animal`的`speak`抽象方法
]
#task("再来设计通讯录")[
- 在讲述面向过程编程中,我们举了一个通讯录的例子,那么现在你能否使用面向对象的思想设计一个通讯录呢?
- 坦克大战!如果你玩过坦克大战的话(4399里的,时代的眼泪啊💧)我们都知道,坦克的行为有,转向,前进,射击等,现在让你设计,你应该也会吧?当然坦克大战里面还有,子弹,地图,围墙等对象呢?你能否设计出原型呢?尝试思考或者写点代码吧。
]
#suggestion("游戏")[
你好奇游戏是怎么制作而成的吗?事实上,游戏就是通过编写程序而成,里面的各种对象的行为都是通过程序定义而执行,而你所看到的精美画面,只不过是通过计算机(cpu,gpu)背后计算后*渲染*而成的。因为游戏背后也是严密的逻辑,一个行为同样可以拆分成好个动作和对应的画面最后呈现到大家面前。如果你想去做一个自己的游戏,请自己去深入学习编程的抽象思维吧
]
== 函数式编程
函数的话,我们都知道,那么函数式编程又是个什么东西呢?所谓的*函数式编程*就是,主要关注使用“函数”来处理数据,而不是通过改变状态或使用命令来控制程序的行为。它就像数学中的函数,给定相同的输入总会得到相同的输出。函数式编程的一个特点就是,允许把函数本身作为参数传入另一个函数,还允许返回一个函数!这么讲还是太抽象了(😣),简单来说,函数式编程就是要求你尽量将运算过程写成一系列的函数调用,具体来看一下下面的这个列子吧
#codes[
通常,如果要求我们完成下面这个运算
`(1+2)*3-4`的话,一般的做法是
```python
a = 1 + 2
b = a * 3
c = b - 4
```
如果使用函数式编程的话,写法是这样的
```python
def add(a,b):
return a + b
def mul(a,b)
return a * b
def sub(a,b)
return a - b
res = sub(mul(add(1,2),3),4)
```
这就是函数式编程
]
至于为什么发明这样的写法(这看起来可复杂多了),那原因可太多了,现在告诉你们大概是无法理解(笔者也只有粗浅的认知😭)。事实上,上面的程序写成下面这样就好看很多了
#codes[
```python
add(1,2).mul(3).sub(4)
```
]
可以看到执行的顺序一目了然,先执行`add`再执行`mul`然后执行`sub`。
下面我们来正式介绍一下Python中函数式编程的几种形式
1. *高阶函数(Higher-order function)*:
编写高阶函数,就是让函数的参数能够接收别的函数,可从如下三种类型来更好的理解高阶函数。
- 函数本身也可以赋值给变量,变量可以指向函数.
#codes[
```python
>>> abs(-10)
10
>>> abs
<built-in function abs>
>>> f = abs
>>> f
<built-in function abs>
```
]
- *传入函数*:变量可以指向函数,函数的参数能接收变量,那么一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数。
#codes[
```python
def add(x, y, f):
return f(x) + f(y)
print(add(-5, 6, abs))
```
]
- *返回函数*:高阶函数除了可以接受函数作为参数外,还可以把函数作为结果值返回。
#codes[
```python
def lazy_sum(*args):
def sum():
ax = 0
for n in args:
ax = ax + n
return ax
return sum
my_list = [1,2,3,6]
sum_func = lazy_sum(my_list)
print(sum_funct())
```
]
当我们调用`lazy_sum()`时,返回的并不是求和结果,而是求和函数,我们将求和函数赋值给`sum_func`,只有当调用`sum_func()`时才真正触发了内部的计算(逻辑运行),这样的机制其实我们称为*惰性计算*
下面是一些Python中常用的高阶函数
#codes[
```python
# map函数, 对可迭代对象中的元素进行变化
def square(x):
return x * x
numbers = [1, 2, 3, 4]
squared_numbers = map(square, numbers)
print(list(squared_numbers)) # 输出: [1, 4, 9, 16]
# filter函数,对可迭代对象中的元素进行过滤
def is_even(num):
return num % 2 == 0
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(is_even, numbers)
print(list(even_numbers)) # 输出: [2, 4, 6]
# sorted函数, 对可迭代对象内部元素按照某个元素进行排序
words = ['banana', 'apple', 'cherry']
sorted_words = sorted(words, key=lambda x: len(x))
print(sorted_words) # 输出: ['apple', 'banana', 'cherry']
# reduce函数,对可迭代对象中的元素两两规约(根据传入的函数)后放入,再继续合并
# 下面这个例子的过程可以认为是 1*2=2,2*3=6, 6*4=24
from functools import reduce
def multiply(x, y):
return x * y
numbers = [1, 2, 3, 4]
product = reduce(multiply, numbers)
print(product) # 输出: 24
# zip函数,对两个可迭代对象进行组装,两两一对,要求两个对象的元素个数相等
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
paired = zip(names, ages)
print(list(paired)) # 输出: [('Alice', 25), ('Bob', 30), ('Charlie', 35)]
```
]
#task("动动手✋")[
- 上面我们已经展示过如何使用`reduce`对一个列表内的数字进行累乘,你能使用`reduce`对一个列表进行进行求和吗?
- 使用`zip`可以同时对两个可迭代对象进行遍历,如下
#codes[
```python
my_list1= [1,2,3]
my_tuple =[4,5,6]
for i,j in zip(my_list,my_tuple):
print(i,j)
```
]
那么你能否自己实现一个简单的`zip`函数呢?
- 相应的,我觉得你应该有能力手动实现`filter`和`map`函数了,下面给出接口
#codes[
```python
def my_filter(func,iterable_obj):
def my_map(func,iterable_obj);
```
]
]
2. *匿名函数*:
- 当我们在传入函数时,有些时候,不需要显式地定义函数,直接传入匿名函数更方便。匿名函数有个限制,就是只能有一个表达式,不用写return,返回值就是该表达式的结果。
- 用匿名函数有个好处,因为函数没有名字,不必担心函数名冲突。此外,匿名函数也是一个函数对象,也可以把匿名函数赋值给一个变量,再利用变量来调用该函数,同样,也可以把匿名函数作为返回值返回.
#codes[
```python
>>> f = lambda x: x * x
>>> f
<function <lambda> at 0x101c6ef28>
>>> f(5)
25
def build(x, y):
return lambda: x * x + y * y
```
]
3. *装饰器*:
- 我们初始定义一个函数,希望增加它的功能但不希望修改其定义,在代码运行期间动态的增加功能的方式,称之为“装饰器”。
本质上,decorator就是一个*返回函数的高阶函数*。看下下面的案例,我们希望在执行一个函数时候能打印该函数的名称
#codes[
```python
def log(func):
def wrapper(*args, **kw):
print('call %s():' % func.__name__)
return func(*args, **kw)
return wrapper
@log
def now():
print('2024-6-1')
>>> now()
call now():
2024-6-1
```
]
下面我们来解释一下上面这段函数
我们首先定义了`log`函数,接受一个`func`的参数,
然后我们在`log`内部声明了一个`wrapper`函数,在里面调用了`func`
然后我们声明了`now`这个函数,并使用了`@log`这个装饰器
当调用`now()`的时候,会先将`now`传入log中,然后按照`log`函数中的逻辑继续执行代码,不仅会运行now()函数本身,还会在运行now()函数前打印一行日志。在这里你也可以认为调用了`now`就是调用了`wrapper`函数
#task("动动手")[
- 编写一个修饰器,要求能够输出被修饰的函数的运行时间
]
#suggestion("关于函数式编程")[
函数式编程还有很多很多很多内容没有讲,这里也只是抛给大家一个引子,后面有机会可以自己去学习相关的内容哦。在这里大家只要将函数式编程简单理解为,你可以将函数作为一个变量赋值,当成一个参数去传递。
]
== 元编程
元编程就是关于创建操作源代码(比如修改、生成或包装原来的代码)的函数和类。 主要技术是使用装饰器、类装饰器和元类。不过还有一些其他技术, 包括签名对象、使用 `exec()` 执行代码以及对内部函数和类的反射技术等。简单说,你可以通过元编程技术来定制化你的源代码化行为。简单来说,元编程就是在程序运行时,动态的修改程序的内容
在Python中,元编程主要依赖于以下几个核心概念:
- *动态类型*:Python是一种动态类型语言,这意味着变量的类型在运行时可以更改。这种灵活性使得Python代码可以在运行时动态地创建、修改和删除类和方法。最开始的时候我们曾提及过,对于一个变量你可以用任何类型的值对其复制,因此该变量的类型也会其值而改变,这就是所谓的动态类型。
- *装饰器*(Decorators):装饰器是一种元编程工具,它允许开发者在不修改原始函数或类代码的情况下,为它们添加额外的功能。装饰器本质上是一个接受函数或类作为参数的可调用对象,并返回一个新的函数或类对象。(上文有提及)
- *反射*(Reflection):反射是指程序能够检查和修改其自身结构(如类、方法、变量等)的能力。Python的内置函数和模块,如dir(), type(), getattr(), setattr(), callable(), 以及inspect模块,都提供了反射功能。
- *泛型*:泛型是一种编程概念,通俗地说,它允许你编写可以处理多种数据类型的代码,而不需要为每种类型单独编写代码。
下面我们来重点介绍下反射和泛型
=== 反射
- Python的反射(Reflection)是指程序能够在运行时获取到自身的信息,并进行操作的能力。这包括获取对象的类、方法、属性等信息,以及动态地调用对象的方法和修改对象的属性等。
- 反射在Python中主要通过以下几种方式实现:
1. `type()` 和 ` isinstance()` 函数:可以用来获取对象的类型或一个对象是否是某个类的实例。
2. `dir()` 函数:可以用来获取一个对象的所有属性和方法。
3. `getattr()` 函数:可以用来获取一个对象的方法或属性。如果指定的属性不存在,它会抛出 `AttributeError` 异常。
4. `setattr()` 函数:可以用来动态地给一个对象设置属性。如果属性不存在,它会创建这个属性。
5. `hasattr()` 函数:可以用来检查一个对象是否具有某个属性。
6. `delattr()` 函数:可以用来删除一个对象的属性。
- 反射使用的场景:
1. 动态导入模块
2. 动态获取对象属性
3. 动态调用对象的方法
看个例子吧
#codes[
```python
class MyClass:
def my_method(self):
return "Hello"
obj = MyClass()
method_name = 'my_method'
if hasattr(obj, method_name):
method = getattr(obj, method_name)
print(method()) # 输出: Hello
```
]
我们来解释一下上面这段代码
首先声明了`Myclass`类,然后创建了`obj`对象
然后我们使用`hasattr`判断`obj`是否有`method_name`这个方法,如有,则使用`getattr`获取`obj`的方法,然后调用方法。假设我们不知道`MyClass`的内部实现,就需要使用这种形式去编写程序的逻辑
=== 泛型
Python 的泛型是*类型提示*(类型标注,类型声明)的一个高级特性,用于指示某些数据结构或函数可以接受多种数据类型,例如使得一个函数的参数能够接收*多种类型的数据*或者使得一个类能够接收并存储不同种类的数据。泛型在 Python 中通常通过模块 typing 实现。泛型的使用有助于提高代码的可读性和健壮性,尤其是在大型项目和团队协作中。
#attention("类型标注")[
前面我们提到了Python是动态类型的语言,对任意变量的赋值是没有限制的。其实如果没有对其类型进行限定,其就是`Any`类型的变量。如果学过c语言,我们都知道在对变量(参数)声明时,必须需要声明其类型,就称为*类型声明*如下,我们声明了一个`int`型的变量`a`
```c
int a;
```
在Python中,没有强制我们必须声明类型,但我们同样可以使用`:类型`的方式对变量的类型进行声明,如下
```python
a:int = 1
```
如果我们需要代码的可读性好一点是,通常是需要类型标注的,一旦进行了类型标注,就不可给该变量赋予其他类型的值。拿上面的这个例子来说,你已经声明`a`为`int`,就不可为其赋予`str`类型的值
特别地,如果你需要对函数返回值的类型进行限定,可以使用`->`
```python
def func() -> int:
pass
```
]
为什么需要泛型呢,事实上,Python作为一个动态类型的语言,不进行类型标注的话,完全不需要泛型。但是事实上,在构建项目时,是需要一定的类型标注的。事实上如果变量类型不可变,考虑以下问题
#codes[
```python
# 处理函数
def process_item(item:int)->int
return item*item
item = 3
print(process_item(item))
```
]
上述代码定义了一个`process_item`的函数用于处理元素,接着我们传入了一个值为`3`,类型为`int`的变量`item`进去,进行处理。如果此时我希望对一个类型为`float`的变量,也能进行相同的操作,你会如何处理呢,由于我们限定了`process_item`传入的参数只能是`int`型的,最直观的想法是再创建一个函数,功能和`process_item`相同,只不过传入的参数是`float`型的,如下
#codes[
```python
def process_item_float(item:float) -> float:
return item * item
item = 3.0
print(process_item_float(item))
```
]
但是这样是否太麻烦了呢?要创建两个函数确实麻烦。函数的逻辑都是相同,我能否只创建一个函数就解决所有类型问题呢?有的,就是使用泛型函数,在python中,如果要使用泛型就要使用`typing`模块,具体如下
#codes[
```python
from typing import TypeVar,
T = TypeVar('T)
def process_item(item:T) -> T:
return T * T
item1 = 2
print(process_item(item1)
item2 = 2.0
print(process_item(item2))
```
]
我们来解释一下上面这个代码
首先我们使用`from`和`import`从`typing`中导入`TypeVar`函数,定义了一个泛型变量`T`
接着我们使用`T`声明了一个泛型函数`process_item`,`process_item`可以接受任意类型的参数,对其进行逻辑处理,该例子中的逻辑是相乘。然后我们就可以传入任意类型的参数进去了,当然,如果传入的类型不支持`*`运算,是会报错的,比如你传入一个`str`型的值就会报错。
通过上面的方式,我们可以提高代码的复用率,当然,如果要使用泛型编程,你必须需要有足够的经验和严密的逻辑,不然传入一个不支持的类型,程序运行过程是会出错的。事实上,如果你有机会学习`c++`,你会发现里面很多地方使用了泛型编程。
下面继续系统介绍两种泛型的使用
1. 创建泛型类,可以使用 typing.Generic 创建自定义的泛型类。
#codes[
```python
from typing import TypeVar, Generic
T = TypeVar('T')
class Stack(Generic[T]):
def __init__(self) -> None:
self.items: List[T] = []
def push(self, item: T) -> None:
self.items.append(item)
def pop(self) -> T:
return self.items.pop()
stack = Stack[int]()
stack.push(1)
stack.push(2)
print(stack.pop()) #
```
]
在这个例子中,Stack 类是一个泛型类,可以用于存储任何类型的元素。在实例化时,你可以指定具体的类型,比如 Stack[int]。
2. 泛型函数,泛型也可以用于定义可以接受多种类型参数的函数。
#codes[
```python
from typing import TypeVar, Generic
T = TypeVar('T')
def first(items: List[T]) -> T:
return items[0]
print(first([1, 2, 3])) # 1
print(first(["apple", "banana", "cherry"])) # apple
```
]
在这里,first 函数可以接受任何类型的列表,并返回列表中的第一个元素。
#attention("注意事项")[
1. 类型检查:Python 的类型提示仅用于静态类型检查,不会影响运行时行为。
2. 兼容性:确保使用泛型的代码与使用的 Python 版本兼容。
3. 可读性:合理使用泛型以提高代码的可读性和维护性,避免过度复杂化。
]
= 工具链
== 调试器
`pdb` 是 Python 的内置调试器(不需要额外下载),提供了一种互动式调试 Python 程序的方式。它允许开发者逐步执行代码、检查变量、设置断点等,从而帮助定位和修复程序中的错误。以下是有关 `pdb` 的一些关键点:
1. *逐步执行*:可以逐行执行代码,帮助理解程序的执行流程。
2. *设置断点*:可以在代码的特定行设置断点,当程序执行到该行时会暂停,方便检查状态。
3. *检查变量*:可以动态查看和修改变量的值,帮助调试逻辑问题。
4. *调用堆栈检查*:可以查看当前的调用堆栈,帮助理解函数调用的上下文。
#suggestion("建议")[
有时候,难免会出现一些涩晦的名词,这是一些后续大家才会接触的内容。我们在能力范围内尽可能地让大家能够入门并学会思考,但当你觉得某些东西看不懂,在不影响你后续学习的情况下,大可先跳过去,不需要强行记忆。
]
=== pdb常用命令
- *`n` (next)*: 执行下一行代码。
- *`c` (continue)*: 继续执行,直到下一个断点。
- *`s` (step)*: 进入当前行的函数调用。
- *`q` (quit)*: 退出调试器。
- *`p` (print)*: 打印变量的值,例如 `p my_variable`。
- *`l` (list)*: 列出当前执行位置附近的代码行。
- *`b` (break)*: 设置断点,例如 `b 12` 在第 12 行设置断点。
使用示例:
要在 Python 程序中使用 `pdb`,可以按以下方式引入:
#codes[
```python
import pdb
def example_function(x):
pdb.set_trace() # 设置断点
y = x + 1
return y
result = example_function(5)
print(result)
```
]
1. 启动调试器
运行程序时,执行到 `pdb.set_trace()` 时会进入调试模式。你可以使用上述命令来调试程序。
2. 命令行调试
你也可以直接在命令行中运行 Python 程序并启动 `pdb`:
```bash
python -m pdb myscript.py
```
这会在程序执行时启动调试器。
#task("尝试调试你的程序")[
- 任意选择你前面写给过的程序,试着用pdb设置断点,查看信息
- 目前很多IDE(Integrated Develop Enviroment 集成开发环境)都自带调试的功能(如Pycharm),VS code作为一款编辑器也具备调试的功能,具体的做法可以参考 #link("https://vscode.github.net.cn/docs/python/python-tutorial")[VS code中使用python]中的调试代码部分
- 除了pdb之外,还有很多更优秀调试的工具,请STFW,选择一款适合你的工具吧
]
== 包管理
*包管理*是指组织、安装、更新和删除软件包(即程序和库)的一种方法和系统。通俗来讲,如果你曾使用过类似软件管家的软件,可以简单认为包管理工具的功能类似于软件管家。我们可以通过软件管家下载、删除、更新软件。类似地,可以通过包管理工具下载、删除、更新软件包
`pip` 是 Python 的一个*包管理工具*,用于安装和管理 Python 程序包(也称为库或模块)。它使得开发者能够轻松地下载、安装和更新第三方库,这些库可以帮助你在项目中实现各种功能,而不需要从头编写所有代码。在我们安装好Python时,pip也已经随之安装好了。
1. *安装工具*: 想象一下,`pip` 就像是一个超市的购物车。你可以把想要的商品(即 Python 库)放入购物车,并通过 `pip` 把它们带回家(安装到你的计算机上)。
2. *库的来源*: `pip` 从 Python 包索引(PyPI)下载库。PyPI 就像是一个巨大的在线商店,里面有数以千计的 Python 库供你选择。
#task("尝试一下")[
打开终端,输入`pip --help`来查看pip的功能和使用方法,我们可以看到终端中输出了大量的信息,告诉我们pip命令的可选参数,以及每个参数的含义
]
#suggestion("建议")[
- 要习惯在终端中这样的交互方式,之后当我们使用Linux操作系统的时候,很多命令都是通过命令行执行的
- 类似于`pip --help`这样"命令"+"参数"的命令有很多,之前我们执行文件的使用的指令`python main.py`是"命令"+"目标文件"的形式,之后我们还会遇到"命令"+"参数"+"目标文件"这样冗长的指令
]
=== pip 简单操作
1. *安装库*: 使用 `pip` 安装库非常简单。比如,想要安装一个名为 `requests` 的库,只需要在终端中输入:
```bash
pip install requests
```
2. *更新和卸载*: 除了安装,`pip` 也可以用来更新库和卸载不再需要的库。例如:
- 更新库:`pip install --upgrade requests`
- 卸载库:`pip uninstall requests`
3. *管理依赖*: 在一个项目中,可能会用到多个库。`pip` 允许你将这些依赖项列在一个文件中(通常是 `requirements.txt`),这样其他人可以轻松地安装你项目所需的所有库:
```bash
pip install -r requirements.txt
```
#task("安装一些常用的库")[
使用pip安装numpy,matplotlib,scikit-learn等常见的第三方库
]
#attention("安装不了?!")[
当你使用pip的时候可能会卡在search的这一步,这是由于PyPI的资源网站位于国外,访问时间非常长,我们可通过配置pip,使得pip从国内的镜像源网站下载第三方库,具体请看下一小节
]
=== 更换库源
前面我们提到,pip通过在PyPI中搜索满足要求的第三方库(模块),但是这样产生的体验并不好,因为PyPI资源网站位于国外,访问时间非常长,我们可以配置pip的源库为国内的镜像网站,具体可以参考 #link("https://blog.csdn.net/haohaizijhz/article/details/120786153")[pip 配置清华源]
#task("配置镜像源")[
- 我们可以通过`pip install 库名称 -i 镜像网站`的方式来临时指定镜像源下载某一个库,但这样极不方便
- 尝试将pip的库源永久设定为清华源
]
== 虚拟环境管理
*虚拟环境*是一种隔离的工作空间,可以让你在不同项目中使用不同的依赖和 Python 版本,而不会相互干扰。为什么需要虚拟环境?试着想一下这样的场景,当你的 requests 库需要 numpy的版本 >= 1.1 而 matplotlib库要求 numpy 的版本小于 < 1.1,这就是*版本冲突*。
就好比,在同一个厨房里,如果我们限定一个厨房只能有一把刀(numpy),一个厨师要求只使用13cm长及以上的刀(requests),另一个厨师要求只能使用13cm以下的刀(matplotlib),这样的情况两个厨师长不得打一架(版本冲突)?
那么我们要如何解决?最好的方式自然是将两个厨师放在不同的厨房里。对应地,就是使用虚拟环境,将 requests 所需要的依赖和 matplotlib 需要的依赖隔离到两个不同的工作空间,在不同的虚拟环境当中安装对应的依赖库(因此,你可以认为虚拟环境就是一个个独立工作的厨房)。下面我们分别介绍python的两种虚拟环境的方案:*venv*和*conda*
=== venv
`venv` 是 Python 3 中自带的用于创建虚拟环境的模块,不需要额外安装,下面我们简单介绍一下如何使用venv的虚拟环境。
1. *创建虚拟环境*:在项目目录中,使用以下命令创建虚拟环境,其中`myenv` 是你要创建的虚拟环境的名字
```bash
python -m venv myenv
```
2. *激活虚拟环境*:创建虚拟环境之后,使用`activate`文件激活虚拟环境,不同操作系统的方式不太一样,激活后,你会在命令提示符中看到虚拟环境的名字,表明你已进入该环境。
- *Windows*:
```bash
myenv\Scripts\activate
```
- *macOS/Linux*:
```bash
source myenv/bin/activate
```
3. *安装依赖*:在激活的虚拟环境中,你同样可以使用 `pip` 安装所需的库。例如:
```bash
pip install requests
```
4. *退出虚拟环境*:可以通过 `deactivate` 命令退出虚拟环境:
```bash
deactivate
```
#task("体验venv")[
试着使用venv创建一个虚拟环境,并在该环境下运行你的程序
]
#task("多个虚拟环境")[
在你的项目下继续创建一个虚拟环境,并尝试在多个虚拟环境之间来回切换
]
#suggestion("建议")[
手册不一定总是对的,因为编写手册的过程难免会出现笔误的情况,或者由于本身对这块知识点比较模糊而给出错误的教程或解释,当你反复尝试书册上面的案例而无法成功时,请自行 STFW ,并向我们提出反馈,感谢🙏。
]
=== conda
Conda 是一个开源的包管理和环境管理系统,旨在简化软件包的安装和管理,特别是针对数据科学、机器学习和科学计算领域的用户。以下是关于 Conda 的一些关键点:
1. *包管理*:Conda 允许用户轻松安装、更新和卸载软件包。它支持多个语言的包,包括 Python、R、Ruby、Lua、Scala、Java、JavaScript、C/C++、FORTRAN 等。
2. *环境管理*:Conda 允许用户创建和管理独立的环境,每个环境可以有不同的依赖包版本。这对于避免依赖冲突非常重要。
3. *跨平台*:Conda 支持 Windows、macOS 和 Linux 等多个操作系统。
*Miniconda*是一个Conda的轻量级的发行版,只包含了必要的工具和基础包,请到 #link("https://docs.anaconda.com/miniconda/")[Miniconda 下载官网]中下载Miniconda,具体的安装过程请参考 #link("https://blog.csdn.net/sunyuhua_keyboard/article/details/136472522")[Miniconda 安装教程]
#task("安装Miniconda")[
请跟随教程安装Miniconda
]
#suggestion("conda 与 venv")[
相比于venv,conda是比较臃肿的,但是对于新手来说操作比较简单,当然还有很多虚拟环境的方案,请STFW了解更多,并选择一种适合自己的虚拟环境方案吧
]
==== conda常用操作
1. *创建新环境*:其中`myenv`为虚拟环境的名称,同时可以指定虚拟环境中Python的版本
```bash
conda create --name myenv python=3.9
```
2. *激活环境*:激活后,你会在命令提示符中看到虚拟环境的名字,表明你已进入该环境。
```bash
conda activate myenv
```
3. *退出虚拟环境*:
```bash
conda deactivate
```
4. *安装包*:
```bash
conda install numpy
```
5. *更新包*:
```bash
conda update numpy
```
6. *列出所有环境*:
```bash
conda env list
```
7. *删除环境*:其中`myenv`为你要删除的环境的名称
```bash
conda remove --name myenv --all
```
#task("使用conda创建虚拟环境")[
- 类似于`pip`,你同样可以使用`conda --help`来查看关于conda命令的使用方法和各种参数的含义。事实上,绝大多数命令都可以使用`命令 --help`的方式来查看对应的帮助文档,之后当你使用Linux系统时,你不可能一下子记住所有命令的使用方法,需要经常使用`--help`参数。
- 现在打开终端,使用conda创建一个虚拟环境吧。
]
#attention("安装conda之后")[
安装conda并配置好环境变量之后,请重新打开终端。你可以看到命令行提示符最前面出现`(base)`,这就是你当前所处的虚拟环境,`base`可以认为是你最开始安装Python的环境。需要注意的是,如果要切换虚拟环境,我们建议先使用`conda deactivate`退出当前虚拟环境,再通过`conda activate`激活新的虚拟环境,否则可能会环境嵌套的问题,就比如,你可能看到,命令行提示符显示`(base)(myenv)`这样的多种环境堆叠的情况
]
#suggestion("conda 与 pip")[
可以看到conda也可以承担安装第三方库的角色,因此conda也是*包管理工具*的一种,记住,包管理工具会记录所有已安装的第三方库。但是这样会产生一个问题,同一个虚拟环境,存在两个包管理工具,如果我们需要安装numpy这个第三方库时,是选择`conda install numpy`还是`pip install numpy`呢?这里同样会出现 *版本冲突* 的问题
其实在安装第三方库时,包管理工具会根据当前环境的依赖要求,选择合适版本的库来安装。比如,当前环境下的conda查看已安装的第三方库的依赖要求(通过`conda install`安装的),要求numpy>=1.1,那么conda就会选择符合要求版本的numpy安装,但是如果同时环境通过 pip 安装的第三方库要求numpy < 1.1,那么最终,无论安装那个版本的numpy,都无法同时满足两个包管理的要求。
根据经验,我们推荐的做法是,如果能够先使用conda安装第三方库,先使用conda,如果conda无法寻找到合适的库,再使用pip。当然另外一种做法是,只把conda当成虚拟环境工具,使用conda创建虚拟环境之后,只使用pip 安装第三方库。以上两种做法遇到的问题是比较少的,千万不要交换地使用两种工具安装!!!
]
到这里,我们就完成了python的入门🎉,在此期间我们也渗透性的教大家一些编程范式。当然大家思考问题的方式和解决问题的能力,才是最宝贵的财富。如果你对本学习手册有任何建议,请反馈给我们,期待我们在下一个部分见面! |
|
https://github.com/Vortezz/fiches-mp2i-maths | https://raw.githubusercontent.com/Vortezz/fiches-mp2i-maths/main/chapter_5.typ | typst | #set page(header: box(width: 100%, grid(
columns: (100%),
rows: (20pt, 8pt),
align(right, text("CHAPITRE 3. COMBINATOIRE")),
line(length: 100%),
)), footer: box(width: 100%, grid(
columns: (50%, 50%),
rows: (8pt, 20pt),
line(length: 100%),
line(length: 100%),
align(left, text("<NAME> - MP2I")),
align(right, text("<NAME> - 2023/2024")),
)))
#set heading(numbering: "I.1")
#set math.vec(delim:"(")
#let titleBox(title) = align(center, block(below: 50pt, box(height: auto, fill: rgb("#eeeeee"), width: auto, inset: 40pt, text(title, size: 20pt, weight: "bold"))))
#titleBox("Combinatoire")
= Cardinaux des ensembles finis
== Ensembles finis et cardinaux
On dit que $E$ et $F$ ont le même cardinal s'il existe une bijection de $E$ vers $F$, on note $|E| = |F|$.
On dit que $E$ est *fini* s'il existe un entier $n$ et une surjection $f : [|1,n|] ->> E$ (ou une injection $g : E arrow.hook [|1,n|]$).
Si $E$ est fini, et que $F subset E$, alors $F$ est fini aussi.
Tout sous-ensemble $E$ de $[|1,n|]$ peut être mis en bijection avec $[|1,p|]$ pour un $p <= n$.
Soit $n, m in NN$, si il existe une bijection de $[|1,n|]$ vers $[|1,m|]$, alors $n = m$.
== Règles de calcul sur les cardinaux
On a $A subset E$, ainsi $|A| = sum_(k in E) bb(1)_A (k)$
On a $A_1, ..., A_n$ des ensembles finis 2 à 2 disjoints, alors $|A_1 union ... union A_n| = |A_1| + ... + |A_n|$
On a $A subset B$, alors $|C_B A| = |B| - |A|$ et $|A| <= |B|$ avec égalité si et seulement si $A = B$
On a $A subset B$, alors $|A times B| = |A| times |B|$
On a la *formule du crible de Poincaré* :
$ |A_1 union ... union A_n| = sum_(k = 1)^n (-1)^(k-1) (sum_(i <= i_1 <= ... <= i_k <= n) |A_i sect ... sect A_i_k|) = sum_(I subset [|1,n|] \ I != emptyset) (-1)^(|I|-1) |sect.big_(i in I) A_i| $
On a $A_1, ..., A_n$ des ensembles finis, alors $|A_1 times ... times A_n| = |A_1| times ... times |A_n|$
== Comparaison de cardinaux en cas d'injectivité ou de surjectivité
On a $f : E -> F$ une application :
- si $f$ est injective, alors $|E| <= |F|$
- si $f$ est surjective, alors $|E| >= |F|$
- si $f$ est bijective, alors $|E| = |F|$
On a $|E|=|F|$, et $f : E -> F$, ainsi les propriétés suivantes sont équivalentes :
- $f$ est injective
- $f$ est surjective
- $f$ est bijective
= Combinatoire
== Combinatoire des ensembles d'applications
On rappelle que $E^F$ est l'ensemble des applications de $F$ vers $E$. On a $|E^F| = |E|^(|F|)$.
Une *p-liste* d'éléments de $F$ (ou *p-uplet*) est un élément $(x_1, .., x_p)$ de $F^p$.
Le nombre de p-listes d'éléments de $F$ est $|F|^p$.
On a $|P(E)| = 2^(|E|)$
*Lemme du berger* : Soit $f : E -> F$, on suppose qu'il existe un entier $k in NN^*$ tel que pour tout $y in F$, $|f^(-1)({y})| = k$. Alors $|E| = k times |F|$.
Soit $A$ et $B$ tel que $|A| = p$ et $|B| = n$, alors si $p<=n$ le nombre d'injections de $A$ vers $B$ est $A^p_n = n!/(n-p)!$. Si $p>n$, alors $A^p_n = 0$.
Soit $|F| = n$ et $p<=n$, le nombre de p-listes d'éléments distincts de $F$ (ou *p-arrangements*) est $A^p_n = n!/(n-p)!$
Soit $E$ un ensemble fini, $|frak(S) E| = |E|!$ et $|S_n|=n!$
== Combinatoire de sous ensembles
Soit $E$ et $F$ deux ensembles de même cardinal, alors $|P_k (E)| = |P_k (F)|$.
Le *coefficent binomial* $vec(n,k)$ est le nombre de parties à $k$ éléments de $[|1,n|]$. On a $vec(n,k) = n!/(k!(n-k)!)$.
Soit $(n,k) in NN times ZZ$,
- Si $n>=0$, et $k in.not [|0,n|], vec(n,k)=0$
- Si $n>=0,$
- $vec(n,0) = vec(n,n) = 1$
- $vec(n,1) = vec(n,n-1) = n$
- $vec(n,2) = vec(n,n-2) = (n(n-1))/2$
Pour tout $(n,k) in ZZ^2$, on a :
- $vec(n,k) = vec(n,n-k)$ (symétrie)
- $k vec(n,k) = n vec(n-1,k-1)$ (formule du comité-président)
- $vec(n,k) = vec(n-1,k-1) + vec(n-1,k)$ (formule de Pascal)
*Formule du binôme de Newton* : Soit $n in NN$ et $a, b in RR$, alors $(a+b)^n = sum_(k = 0)^n vec(n,k) a^(n-k) b^k$
= Bijection, Déesse de la Combinatoire
Pour montrer que deux ensembles ont le même cardinal, on peut montrer qu'il existe une bijection entre les deux.
= Preuves combinatoires d'identités
Pour démontrer _combinatoirement_ :
+ Il faut trouver un modèle adapté à la formule, soit un ensemble d'objets dont le dénombrement est égal à celui d'un des membres de l'égalité. Il faut s'aider du membre le plus simple de l'égalité.
+ Dénombrer cet ensemble de 2 façons différentes. On procède d'une part à un dénombrement après un tri (soit une partition de l'ensemble) se traduisant par une somme, et d'autre part à un dénombrement en comptant les objets un par un.
#emoji.warning Évidemment on ne fait ça que sur des entiers au risque d'avoir des petits soucis.
On a les formules suivantes :
- $sum_(k = 0)^n vec(n,k) = 2^n$
- $sum_(k = 0)^n vec(N,k) vec(M,n-k) = vec(N+M,n)$ (*Vandermonde*)
- $sum_(k = 0)^p vec(n+k,n) = vec(n+p+1,n+1)$ (*Sommation sur une colonne*)
Un signe $(-1)^k$ correspond à une comparaison de parités de cardinaux. On peut passer d'un cardinal pair à un cardinal import avec la différence symétrique ($ Delta$) avec un ${x}$ soit $X |-> X Delta {x}$. C'est le *principe de l'interrupteur*. |
|
https://github.com/hekzam/typst-lib | https://raw.githubusercontent.com/hekzam/typst-lib/main/README.md | markdown | Apache License 2.0 | hekzam's typst lib
===================
Typst library to help the generation of exam sheets.
How to run tests?
-----------------
1. Install Nix: https://nixos.org/download
2. Enable the `nix` command and flakes in your Nix configuration: write `experimental-features = nix-command flakes` to `~/.config/nix/nix.conf`.
3. Enter the development shell: `nix develop .#dev`
4. From the `test` directory, run `pytest`. This should run tests, return 0 and populate `/tmp/test-out` with various test files.
hekzam
|
https://github.com/Mc-Zen/pillar | https://raw.githubusercontent.com/Mc-Zen/pillar/main/tests/table/test.typ | typst | MIT License | #set page(width: auto, height: auto, margin: 1pt)
#import "/src/pillar.typ"
#pillar.table(
cols: "lcr",
[ABC], [DEF], [GHI], [J], [K], [L]
)
#pagebreak()
#pillar.table(
cols: "|l|c|r|",
[ABC], [DEF], [GHI], [J], [K], [L]
)
#pagebreak()
// Check interoperability
#pillar.table(
cols: "|lcr|",
column-gutter: (5pt),
[ABC], table.vline(stroke: red), [DEF], [GHI], [J], [K], [L]
)
#pagebreak()
// Num align
#pillar.table(
cols: "l|C|r",
column-gutter: (5pt),
[A], [2.12], [b],
[A], [100], [b]
)
#pagebreak()
// Num align manual with dictionary
#pillar.table(
cols: "l|c|r",
format: (none, (digits: 1, fixed: 2), none),
column-gutter: (5pt),
[A], [1e2], [b],
[A], [1e3], [b]
)
|
https://github.com/pku-typst/unilab | https://raw.githubusercontent.com/pku-typst/unilab/main/lib.typ | typst | MIT License | #import "template.typ": objectives, principles, apparatus, procedure, data, analysis, labreport
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/ops-invalid-01.typ | typst | Other | // Error: 10 expected expression
#test({1+}, 1)
|
https://github.com/yhtq/Notes | https://raw.githubusercontent.com/yhtq/Notes/main/抽象代数/作业/hw11.typ | typst | #import "../../template.typ": *
// Take a look at the file `template.typ` in the file panel
// to customize this template and discover how it works.
#show: note.with(
title: "作业11",
author: "YHTQ ",
date: none,
logo: none,
withOutlined: false
)
= P119
== 1(1)
容易验证它在 $QQ(sqrt(2), sqrt(3))$ 上分裂,同时它的分裂域中显然包含 $sqrt(2), sqrt(3)$,因此这就是它的分裂域
== 2
注意到:
$
(x^(p^n) - 1) = (x - 1)^(p^n)
$
因此它在 $"GF" (p)$ 上已经分裂
== 4
取 $f(x)$ 在 $E$ 上的分裂域 $K'$\
由于 $K'$ 也是 $F$ 的扩域,因此 $K' >= K$\
反之,由于 $K$ 也是 $E$ 的扩域,因此 $K >= K'$\
综合即得 $K = K'$
== 5
- 充分性:假设 $E$ 关于 $quotient(K, F)$ 稳定,则设 $p(x) in f(x)$ 是 $F[x]$ 上不可约多项式,且在 $E$ 上有根 $alpha$\
设 $beta$ 是 $p(x)$ 的另外一个根,并设 $K$ 是 $f(x) in F[x]$ 的分裂域。\
取熟知的 $F-$ 域同构:$sigma: F(alpha) -> F(beta)$ 由于 $f(x)$ 在 $F(alpha), F(beta)$ 上的分裂域都是 $K$,由熟知命题,存在 $K$ 上的自同构 $sigma': K -> K$,使得:
$
sigma'|_F(alpha) = sigma => sigma'|_F = id
$
由条件,该自同构应该保持 $E$ 稳定,而 $sigma(alpha) = beta$,因此 $beta in E$\
这就表明 $E$ 具有了 $p(x)$ 的所有根
- 必要性:显然
== 10
- 验证它们在 $"GF"(3)$ 中没有零点,足以说明它们都不可约\
- 注意到:
$
x^2 - x - 1 = x^2 + 2 x + 2 = (x+1)^2 + 1
$
因此 $beta - 1$ 一定是 $f(x)$ 的根,从而存在同构 $sigma: "GF"(3)(alpha) -> "GF"(3)(beta-1) = "GF"(3)(beta)$,形如:
$
a + b alpha -> a + b(beta - 1)
$
== 13
#lemma[][
不可约多项式 $f(x)$ 在 $F_(p^n)$ 中有根当且仅当 $f(x) | x^(p^n) - x$
]
#proof[
充分性是显然的。对于必要性,设 $f(x)$ 在 $F_(p^n)$ 中有根 $alpha$,显然 $x^(p^n) - x$ 成为 $alpha$ 的一个零化多项式,而 $f(x)$ 是不可约多项式,进而是最小多项式,自然有结论成立
]
注意到 $F_(p^n)$ 就是 $x^(p^n) - x$ 的分裂域,进而这是正规扩张,$f(x)$ 有根当且仅当分裂。\
#lemma[][
$F_(p^m)$ 成为 $F_(p^n)$ 的子域当且仅当 $m | n$
]
#proof[
- 充分性:注意到当 $m | n$ 时,有 $x^(p^m) - x | x^(p^n) - x$,进而当然有 $x^(p^m) - x$ 的分裂域 $F_(p^m)$ 成为 $x^(p^n) - x$ 的分裂域 $F_(p^n)$ 的子域
- 必要性:注意到 $[F_(p^n) : F_p] = n$,因此结论是容易的
]
结合两个引理,结论是容易的。事实上,$f(x)$ 的分裂域一定是一个有限域 $K$,且 $[K : F_p] = m$ (这是因为做一次有限域上任何扩张都是正规的,进而添加一个根即分裂)\
换言之,$K = F_(p^m)$ ,而我们当然有 $f(x)$ 在 $F_(p^n)$ 中有根当且仅当它的分裂域 $K$ 成为 $F_(p^n)$ 的子域(同样利用有根即分裂),进而由引理知这当且仅当 $m | n$
= 补充题
==
设 $K, L$ 在 $F$ 上的基分别为 $alpha_i$
- 假设 $phi$ 是 $F-$ 同态,当然有:
$
phi(a + b) = phi(a) + phi(b)\
phi(lambda a) = phi(lambda) phi(a) = lambda phi(a), forall lambda in F
$
因此 $phi$ 是线性映射
- 假设 $phi$ 是线性映射,则:
$
phi(lambda dot 1) = lambda phi(1) = lambda dot 1 = lambda, forall lambda in F
$
表明 $phi$ 保持 $F$ 不动,是 $F-$ 同态。
==
在分裂域存在性的证明中,我们有:
$
[F(alpha) : F] | n
$
其中 $alpha$ 是 $f(x) in E[x]$ 的某个根。\
递归进行即得 $[E:F] | n!$\
当 $f(x)$ 不可约时,当然有:
$
[F(alpha) : F] = n | [E : F]
$
从而结论成立
==
+ 充分性是显然的,只说明必要性。假设 $[K : F] = 2$,则任取 $alpha in K - F$, $alpha$ 当然在 $F$ 中代数。\
显然有:
$
[F(alpha) : F] | 2 => [F(alpha) : F] = 1 or 2\
[F(alpha) : F] != 1 => [F(alpha) : F] = 2 = [K : F]
$
因此 $K = F(alpha)$
// + 假设 $p(x) in F[x]$ 是在 $K$ 中有根 $beta = a + b alpha in K - F$ 的不可约多项式, 取 $F-$ 自同构:
// $
// phi := [a + b alpha | a + b alpha -> a - b alpha]
// $
// 显然 $phi(x) = x <=> x in F$\
// 同时,注意到:
// $
// 0 = phi(p(beta)) = p(phi(beta))
// $
// 从而 $phi(beta)$ 是 $p(x)$ 的根,且 $beta in K - F => phi(beta) != beta$,因此 $p(x)$ 在 $K$ 上恰有不同两根 $beta, phi(beta)$,这就证明了正规扩张性
+ 设 $alpha$ 在 $F$ 上最小多项式为 $m(x), deg m(x) = 2$\
显然 $m(x)$ 在 $K$ 上有一个根,进而可以分解为两个一次因式,也即有两个根。\
同时 $m(x)$ 显然不能在更小的域上分裂,因此 $K$ 就是它的分裂域,扩张确实是正规扩张。
==
+ 错误\
$[QQ(root(3, 2), 1^(1/3))]$ 作为 $x^3 - 2$ 的分裂域是正规扩张,但 $[QQ(root(3, 2))]$ 不是
+ 错误\
注意到:
$
QQ(sqrt(2)) : QQ\
QQ(sqrt(sqrt(2))) : QQ(sqrt(2))
$
都是二次扩张,进而都正规,但显然:
$
QQ(sqrt(sqrt(2))) : QQ
$
不是正规扩张
==
枚举 $f(x) in E[x]$ 的各种分解可能性
- 不可约
- 有一次因式,从而有根。但二次扩张是正规扩张,它应该具有所有的根。然而这表明扩张次数至少为 $6$ 矛盾
- 有二次因式:\
注意到二次扩张形如 $F(alpha)$,我们可以取得 $E$ 上的 $F$ 自同构 $phi$ 将 $alpha$ 映到其最小多项式的另一个根。\
假设 $f(x) = p(x)g(x), deg p(x) = 2$ 且 $p(x) in E[x]$ 不可约。不难发现:
$
p(x) "不可约" <=> phi(p(x)) "不可约"\
p(x) | f(x) => phi(p(x)) | phi(f(x)) = f(x)\
p(x) in.not F[x] => p(x) != phi(p(x))
$
不妨设 $p(x)$ 首一 ,$phi(p(x))$ 不可能与 $p(x)$ 相伴。如若不然,设 $phi(a_i) = lambda a_i$,考虑首项发现 $phi(a_i) = a_i => phi(p(x)) = p(x)$,矛盾
表明 $f(x)$ 至少有两个不可约二次因子,进而是三个不可约二次因子的乘积。\
- 我们还需要证明 $f(x)$ 不会有二重二次因子,否则设 $p(x)^2 | f(x)$,显然有:
$
(phi(p(x)))^2 | f(x)
$
但 $phi(p(x))$ 与 $p(x)$ 应当互素,进而:
$
(p(x) phi(p(x)))^2 | f(x)
$
但是考察次数,这是荒谬的
- 因此,$f(x)$ 有三个不同的不可约二次因式 ${p_1, p_2, p_3}$。同时注意到 $phi$ 是单射,因此群 ${id, phi}$ 在其上的作用给出 ${id, phi}$ 同构于 $S_3$ 的某个二阶子群。但这样的子群总是对换,进而 $exists i, phi(p_i) = p_i$,矛盾
- 可约但无一次,二次不可约因式,此时只能是两个三次不可约因式的乘积。\
==
容易验证 $i in.not QQ(sqrt(3))$,因此 $[QQ(sqrt(3), i) : QQ] = 4$\
而 $[QQ(root(3, 2)) : QQ] = 3$ 与 $4$ 互素,因此:
$
[QQ(sqrt(3), i, root(3, 2)) : QQ] = 12
$
通过在 $(x-y)^3 = 2$ 中利用 $y^2 = 3$ 消去 $y$ 可得 $sqrt(3) + root(3, 2)$ 的一个六次零化多项式 $f(x)$。同时容易发现 $[QQ(sqrt(3) + root(3, 2)) : QQ] = [QQ(sqrt(3), root(3, 2)) : QQ] = 6$,因此这是一个最小多项式。\
同时,不难发现我们任取 $y^2 = 3$ 的根 $alpha$ 和 $z^3 = 2$ 的根 $beta$,均有 $f(beta + alpha) = 0$,因此:
$
plus.minus sqrt(3) + root(3, 2) xi^i, i =0, 1, 2
$
(其中 $xi = 1/2 + sqrt(3)/2 i$ 是三次单位根)\
共计六个数都是 $f(x)$ 的根,恰好就是 $f(x)$ 的所有根,且它们都在 $QQ(sqrt(3), i, root(3, 2))$ 上,进而多项式 $f(x)$ 分裂。\
另一方面,容易发现 $sqrt(3), i, root(3, 2)$ 都可被这六个根生成,因此 $sqrt(3), i, root(3, 2)$ 就是该多项式的分裂域。
==
前面已经证明了 $K = F(alpha)$。设 $alpha$ 的极小多项式为:
$
x^2 + a x + b = 0
$
由于 $char F != 2$,我们仍然可以用配方法解出根:
$
x = -a/2 plus.minus sqrt(a^2 - 4b)/2
$
显然 $alpha in F(sqrt(a^2 - 4b))$,考虑扩张次数可得 $F(alpha) = F(sqrt(a^2 - 4b))$
==
+ 注意到 $f(x)$ 在 $ZZ_2[x]$ 中没有根,进而不可约,从而在 $ZZ[x]$ 中不可约,也在 $QQ[x]$ 中不可约\
+ 令 $x = t + 1/t$,代入 $f(x) = 0$ 得:
$
0 = (t + 1/t)^3 - 3(t + 1/t) + 1 = t^3 + 3t + 3/t + 1/t^3 - 3t - 3/t + 1 \
= t^3 + 1/t^3 + 1\
<=> t^6 + t^3 + 1 = 0
$
当且仅当 $t^3$ 是 $x^2 + x + 1 = 0$ 的根,也即三次单位根 $e^((2 pi i)/3), e^((4 pi i)/3)$,容易发现 $alpha, beta, gamma$ 均符合要求
+ 注意到:
$
alpha^2 = omega^2 + omega^(-2) + 2 in F(alpha) => beta = omega^2 + omega^(-2) in F(alpha)\
beta^2 = omega^4 + omega^(-4) + 2 in F(alpha) => gamma = omega^4 + omega^(-4) in F(alpha)
$
因此 $f(x)$ 在 $F(alpha)$ 中分裂,同时 $alpha$ 当然在 $f(x)$ 的分裂域中,因此 $F(alpha)$ 就是 $f(x)$ 的分裂域
+ 显然 $QQ(alpha)$ 上的自同构都应该保持 $QQ$ 不变,同时作用在 ${alpha, beta, gamma}$ 上给出一个置换 $sigma$。\
注意到 $1, alpha, alpha^2$ 是域扩张的一组基,因此除了平凡同构外,显然不应有 $sigma(alpha) = alpha$,其余两根同理。\
换言之,$sigma$ 只能是三轮换。\
同时,任给三轮换 $sigma$,变换:
$
a + b alpha + c alpha^2 -> a + b sigma(alpha) + c sigma(alpha)^2
$
(注意到 $1, sigma(alpha), sigma(alpha^2)$ 也是一组基)给出一个 $QQ-$ 自同构\
且这是唯一一个在 ${alpha, beta, gamma}$ 上的作用为 $sigma$ 的自同构,因此所求自同构群就是由 $(123)$ 生成的子群。\
==
令 $E = QQ[root(p, 2), xi_p]$
+ 显然 $f(x)$ 在 $E$ 上分裂。反之,由于 $f(x)$ 的所有根形如:
$
root(p, 2) xi_p^i i=0,1, 2,..., p-1
$
故 $root(p, 2), xi_p$ 都在 $f(x)$ 分裂域中,进而 $E$ 就是分裂域
+ \
- 利用补充题 11 的结论,$root(p, 2)$ 的最小多项式就是 $x^p - 2$ ,因此 $[QQ(root(p, 2)):QQ] = p$
- 其次,熟知 $xi_p$ 的最小多项式为:
$
(x^p - 1)/(x-1)
$
(由埃森斯坦判别法)它是 $p-1$ 次不可约多项式,因此 $[QQ(xi_p):QQ] = p-1$
- 由于 $p$ 与 $p-1$ 互素,故 $[E:QQ] = p(p-1)$
+ \
同样利用补充题 11 的结论,若它可约,则它应当有根 $alpha$,但 $alpha$ 的最小多项式的次数为 $p$ ,考虑扩张次数这是荒谬的。
==
由熟知结论,存在 $E$ 上的 $F-$ 自同构 $phi$ 使得:
$
phi(alpha) = beta
$
设 $alpha, beta$ 在 $f(x)$ 的重数分别为 $r_1, r_2$,则有:
$
(x - alpha)^(r_1) | f(x) => (phi(x - alpha))^(r_1) | phi(f(x)) = f(x) => (x- beta)^(r_1) | f(x) => r_2 >= r_1
$
同理可得 $r_1 >= r_2$,进而 $r_1 = r_2$,结论正确
==
注意到 $x^p - a$ 的所有根恰为:
$
x_i := root(p, a) xi_p^i, i = 0, 1, 2, ..., p-1
$
设它在域 $F[x]$ 上有不可约因子 $p(x)$,从而 $p(x)$ 在 $CC[x]$ 中一定形如:
$
product_j^k (x - x_(i_j))
$
观察其常数项,恰为:
$
product_j^k root(p, a) xi_p^(i_j) = a^(k/p) xi^(sum_j^k i_j) in F
$
然而我们发现:
$
(a^(k/p) xi^(sum_j^k i_j))^p = a
$
表明 $a^(k/p) xi^(sum_j^k i_j)$ 是 $F$ 中一个 $x^p - a$ 的根,与条件矛盾! |
|
https://github.com/Maeeen/thesis_template_typst | https://raw.githubusercontent.com/Maeeen/thesis_template_typst/master/README.md | markdown | # EPFL thesis/project report Typst template
Same as [HexHive's template](https://github.com/HexHive/thesis_template), but in Typst, plus or minus some typography details.
This is a **work-in-progress** :warning:.
## Documentation
The documentation of each function is available in the `documentation.pdf` file.
## Before using Typst…
Be aware that Typst is in a very early stage of development. I, personally, not recommend using Typst if:
- You are already familiar with LaTeX and you are happy with it.
- Any more complex bibliography stuff than a `bibliography.bib` file.
- You already have personal LaTeX macros.
However, I recommend using this template if:
- You are already familiar with Typst and its quirks.
- You want to give it a try, but you don't want to start from scratch.
- :warning: This template is -- very probably -- feature lacking compared to HexHive's template.
As a warning, with Typst, you can not:
- include `.pdf` graphics
- have floating figures
- TODO: find more limitations
## Official-ness of this template
I have no affiliation with EPFL nor HexHive. This template is not official in any way, but it is based on HexHive's template.
If you want to give it a try and have no rules about strictly using LaTeX nor the official template, feel free to use it and tweak-it to your liking!
## Tips
All the tips from HexHive's template are valid here too.
|
|
https://github.com/typst-jp/typst-jp.github.io | https://raw.githubusercontent.com/typst-jp/typst-jp.github.io/main/docs/changelog/0.9.0.md | markdown | Apache License 2.0 | ---
title: 0.9.0
description: Changes in Typst 0.9.0
---
# Version 0.9.0 (October 31, 2023)
## Bibliography management
- New bibliography engine based on [CSL](https://citationstyles.org/) (Citation
Style Language). Ships with about 100 commonly used citation styles and can
load custom `.csl` files.
- Added new [`form`]($cite.form) argument to the `cite` function to produce
different forms of citations (e.g. for producing a citation suitable for
inclusion in prose)
- The [`cite`] function now takes only a single label/key instead of allowing
multiple. Adjacent citations are merged and formatted according to the
citation style's rules automatically. This works both with the reference
syntax and explicit calls to the `cite` function. **(Breaking change)**
- The `cite` function now takes a [label] instead of a string
**(Breaking change)**
- Added [`full`]($bibliography.full) argument to bibliography function to print
the full bibliography even if not all works were cited
- Bibliography entries can now contain Typst equations (wrapped in `[$..$]` just
like in markup), this works both for `.yml` and `.bib` bibliographies
- The hayagriva YAML format was improved. See its
[changelog](https://github.com/typst/hayagriva/blob/main/CHANGELOG.md) for
more details. **(Breaking change)**
- A few bugs with `.bib` file parsing were fixed
- Removed `brackets` argument of `cite` function in favor of `form`
## Visualization
- Gradients and colors (thanks to [@Dherse](https://github.com/Dherse))
- Added support for [gradients]($gradient) on shapes and text
- Supports linear, radial, and conic gradients
- Added support for defining colors in more color spaces, including
[Oklab]($color.oklab), [Linear RGB(A)]($color.linear-rgb),
[HSL]($color.hsl), and [HSV]($color.hsv)
- Added [`saturate`]($color.saturate), [`desaturate`]($color.desaturate), and
[`rotate`]($color.rotate) functions on colors
- Added [`color.map`]($color/#predefined-color-maps) module with predefined
color maps that can be used with gradients
- Rename `kind` function on colors to [`space`]($color.space)
- Removed `to-rgba`, `to-cmyk`, and `to-luma` functions in favor of a new
[`components`]($color.components) function
- Improved rendering of [rectangles]($rect) with corner radius and varying
stroke widths
- Added support for properly clipping [boxes]($box.clip) and
[blocks]($block.clip) with a border radius
- Added `background` parameter to [`overline`], [`underline`], and [`strike`]
functions
- Fixed inaccurate color embedding in PDFs
- Fixed ICC profile handling for images embedded in PDFs
## Text and Layout
- Added support for automatically adding proper
[spacing]($text.cjk-latin-spacing) between CJK and Latin text (enabled by
default)
- Added support for automatic adjustment of more CJK punctuation
- Added [`quote`] element for inserting inline and block quotes with optional
attributions
- Added [`raw.line`]($raw.line) element for customizing the display of
individual lines of raw text, e.g. to add line numbers while keeping proper
syntax highlighting
- Added support for per-side [inset]($table.inset) customization to table
function
- Added Hungarian and Romanian translations
- Added support for Czech hyphenation
- Added support for setting custom [smart quotes]($smartquote)
- The default [figure separator]($figure.caption.separator) now reacts to the
currently set language and region
- Improved line breaking of links / URLs (especially helpful for bibliographies
with many URLs)
- Improved handling of consecutive hyphens in justification algorithm
- Fixed interaction of justification and hanging indent
- Fixed a bug with line breaking of short lines without spaces when
justification is enabled
- Fixed font fallback for hyphen generated by hyphenation
- Fixed handling of word joiner and other no-break characters during hyphenation
- Fixed crash when hyphenating after an empty line
- Fixed line breaking of composite emoji like 🏳️🌈
- Fixed missing text in some SVGs
- Fixed font fallback in SVGs
- Fixed behavior of [`to`]($pagebreak.to) argument on `pagebreak` function
- Fixed `{set align(..)}` for equations
- Fixed spacing around [placed]($place) elements
- Fixed coalescing of [`above`]($block.above) and [`below`]($block.below)
spacing if given in em units and the font sizes differ
- Fixed handling of `extent` parameter of [`underline`], [`overline`], and
[`strike`] functions
- Fixed crash for [floating placed elements]($place.float) with no specified
vertical alignment
- Partially fixed a bug with citations in footnotes
## Math
- Added `gap` argument for [`vec`]($math.vec.gap), [`mat`]($math.mat.gap), and
[`cases`]($math.cases.gap) function
- Added `size` argument for [`abs`]($math.abs), [`norm`]($math.norm),
[`floor`]($math.floor), [`ceil`]($math.ceil), and [`round`]($math.round)
functions
- Added [`reverse`]($math.cases.reverse) parameter to cases function
- Added support for multinomial coefficients to [`binom`]($math.binom) function
- Removed `rotation` argument on [`cancel`]($math.cancel) function in favor of a
new and more flexible `angle` argument **(Breaking change)**
- Added `wide` constant, which inserts twice the spacing of `quad`
- Added `csch` and `sech` [operators]($math.op)
- `↼`, `⇀`, `↔`, and `⟷` can now be used as [accents]($math.accent)
- Added `integral.dash`, `integral.dash.double`, and `integral.slash`
[symbols]($category/symbols/sym)
- Added support for specifying negative indices for
[augmentation]($math.mat.augment) lines to position the line from the back
- Fixed default color of matrix [augmentation]($math.mat.augment) lines
- Fixed attachment of primes to inline expressions
- Math content now respects the text [baseline]($text.baseline) setting
## Performance
- Fixed a bug related to show rules in templates which would effectively disable
incremental compilation in affected documents
- Micro-optimized code in several hot paths, which brings substantial
performance gains, in particular in incremental compilations
- Improved incremental parsing, which affects the whole incremental compilation
pipeline
- Added support for incremental parsing in the CLI
- Added support for incremental SVG encoding during PDF export, which greatly
improves export performance for documents with many SVG
## Tooling and Diagnostics
- Improved autocompletion for variables that are in-scope
- Added autocompletion for package imports
- Added autocompletion for [labels]($label)
- Added tooltip that shows which variables a function captures (when hovering
over the equals sign or arrow of the function)
- Diagnostics are now deduplicated
- Improved diagnostics when trying to apply unary `+` or `-` to types that only
support binary `+` and `-`
- Error messages now state which label or citation key isn't present in the
document or its bibliography
- Fixed a bug where function argument parsing errors were shadowed by function
execution errors (e.g. when trying to call [`array.sorted`]($array.sorted) and
passing the key function as a positional argument instead of a named one).
## Export
- Added support for configuring the document's creation
[`date`]($document.date). If the `date` is set to `{auto}` (the default), the
PDF's creation date will be set to the current date and time.
- Added support for configuring document [`keywords`]($document.keywords)
- Generated PDFs now contain PDF document IDs
- The PDF creator tool metadata now includes the Typst version
## Web app
- Added version picker to pin a project to an older compiler version
(with support for Typst 0.6.0+)
- Fixed desyncs between editor and compiler and improved overall stability
- The app now continues to highlight the document when typing while the document
is being compiled
## Command line interface
- Added support for discovering fonts through fontconfig
- Now clears the screen instead of resetting the terminal
- Now automatically picks correct file extension for selected output format
- Now only regenerates images for changed pages when using `typst watch` with
PNG or SVG export
## Miscellaneous Improvements
- Added [`version`] type and `sys.version` constant specifying the current
compiler version. Can be used to gracefully support multiple versions.
- The U+2212 MINUS SIGN is now used when displaying a numeric value, in the
[`repr`] of any numeric value and to replace a normal hyphen in text mode when
before a digit. This improves, in particular, how negative integer values are
displayed in math mode.
- Added support for specifying a default value instead of failing for `remove`
function in [array]($array.remove) and [dictionary]($dictionary.remove)
- Simplified page setup guide examples
- Switched the documentation from using the word "hashtag" to the word "hash"
where appropriate
- Added support for [`array.zip`]($array.zip) without any further arguments
- Fixed crash when a plugin tried to read out of bounds memory
- Fixed crashes when handling infinite [lengths]($length)
- Fixed introspection (mostly bibliography) bugs due to weak page break close to
the end of the document
## Development
- Extracted `typst::ide` into separate `typst_ide` crate
- Removed a few remaining `'static` bounds on `&dyn World`
- Removed unnecessary dependency, which reduces the binary size
- Fixed compilation of `typst` by itself (without `typst-library`)
- Fixed warnings with Nix flake when using `lib.getExe`
## Contributors
<contributors from="v0.8.0" to="v0.9.0" />
|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/092.%20lies.html.typ | typst | lies.html
Lies We Tell Kids
May 2008Adults lie constantly to kids. I'm not saying we should stop, but
I think we should at least examine which lies we tell and why.There may also be a benefit to us. We were all lied to as kids,
and some of the lies we were told still affect us. So by studying
the ways adults lie to kids, we may be able to clear our heads of
lies we were told.I'm using the word "lie" in a very general sense: not just overt
falsehoods, but also all the more subtle ways we mislead kids.
Though "lie" has negative connotations, I don't mean to suggest we
should never do this—just that we should pay attention when
we do.
[1]One of the most remarkable things about the way we lie to kids is
how broad the conspiracy is. All adults know what their culture
lies to kids about: they're the questions you answer "Ask
your parents." If a kid asked who won the World Series in 1982
or what the atomic weight of carbon was, you could just tell him.
But if a kid asks you "Is there a God?" or "What's a prostitute?"
you'll probably say "Ask your parents."Since we all agree, kids see few cracks in the view of the world
presented to them. The biggest disagreements are between parents
and schools, but even those are small. Schools are careful what
they say about controversial topics, and if they do contradict what
parents want their kids to believe, parents either pressure the
school into keeping
quiet or move their kids to a new school.The conspiracy is so thorough that most kids who discover it do so
only by discovering internal contradictions in what they're told.
It can be traumatic for the ones who wake up during the operation.
Here's what happened to Einstein:
Through the reading of popular scientific books I soon reached
the conviction that much in the stories of the Bible could not
be true. The consequence was a positively fanatic freethinking
coupled with the impression that youth is intentionally being
deceived by the state through lies: it was a crushing impression.
[2]
I remember that feeling. By 15 I was convinced the world was corrupt
from end to end. That's why movies like The Matrix have such
resonance. Every kid grows up in a fake world. In a way it would
be easier if the forces behind it were as clearly differentiated
as a bunch of evil machines, and one could make a clean break just by
taking a pill.
ProtectionIf you ask adults why they lie to kids, the most common reason they
give is to protect them. And kids do need protecting. The environment
you want to create for a newborn child will be quite unlike the
streets of a big city.That seems so obvious it seems wrong to call it a lie. It's certainly
not a bad lie to tell, to give a baby the impression the world is
quiet and warm and safe. But this harmless type of lie can turn
sour if left unexamined.Imagine if you tried to keep someone in as protected an environment
as a newborn till age 18. To mislead someone so grossly about the
world would seem not protection but abuse. That's an extreme
example, of course; when parents do that sort of thing it becomes
national news. But you see the same problem on a smaller scale in
the malaise teenagers feel in suburbia.The main purpose of suburbia is to provide a protected environment
for children to grow up in. And it seems great for 10 year olds.
I liked living in suburbia when I was 10. I didn't notice how
sterile it was. My whole world was no bigger than a few friends'
houses I bicycled to and some woods I ran around in. On a log scale
I was midway between crib and globe. A suburban street was just
the right size. But as I grew older, suburbia started to feel
suffocatingly fake.Life can be pretty good at 10 or 20, but it's often frustrating at
15. This is too big a problem to solve here, but certainly one
reason life sucks at 15 is that kids are trapped in a world designed
for 10 year olds.What do parents hope to protect their children from by raising them
in suburbia? A friend who moved out of Manhattan said merely that
her 3 year old daughter "saw too much." Off the top of my head,
that might include: people who are high or drunk, poverty, madness,
gruesome medical conditions, sexual behavior of various degrees of
oddness, and violent anger.I think it's the anger that would worry me most if I had a 3 year
old. I was 29 when I moved to New York and I was surprised even
then. I wouldn't want a 3 year old to see some of the disputes I
saw. It would be too frightening. A lot of the things adults
conceal from smaller children, they conceal because they'd be
frightening, not because they want to conceal the existence of such
things. Misleading the child is just a byproduct.This seems one of the most justifiable types of lying adults do to
kids. But because the lies are indirect we don't keep a very strict
accounting of them. Parents know they've concealed the facts about
sex, and many at some point sit their kids down and explain more.
But few tell their kids about the differences between the real world
and the cocoon they grew up in. Combine this with the confidence
parents try to instill in their kids, and every year you get a new
crop of 18 year olds who think they know how to run the world.Don't all 18 year olds think they know how to run the world? Actually
this seems to be a recent innovation, no more than about 100 years old.
In preindustrial times teenage kids were junior members of the adult
world and comparatively well aware of their shortcomings. They
could see they weren't as strong or skillful as the village smith.
In past times people lied to kids about some things more than we
do now, but the lies implicit in an artificial, protected environment
are a recent invention. Like a lot of new inventions, the rich got
this first. Children of kings and great magnates were the first
to grow up out of touch with the world. Suburbia means half the
population can live like kings in that respect.
Sex (and Drugs)I'd have different worries about raising teenage kids in New York.
I'd worry less about what they'd see, and more about what they'd
do. I went to college with a lot of kids who grew up in Manhattan,
and as a rule they seemed pretty jaded. They seemed to have lost
their virginity at an average of about 14 and by college had tried
more drugs than I'd even heard of.The reasons parents don't want their teenage kids having sex are
complex. There are some obvious dangers: pregnancy and sexually
transmitted diseases. But those aren't the only reasons parents
don't want their kids having sex. The average parents of a 14 year
old girl would hate the idea of her having sex even if there were
zero risk of pregnancy or sexually transmitted diseases.Kids can probably sense they aren't being told the whole story.
After all, pregnancy and sexually transmitted diseases are just as
much a problem for adults, and they have sex.What really bothers parents about their teenage kids having sex?
Their dislike of the idea is so visceral it's probably inborn. But
if it's inborn it should be universal, and there are plenty of
societies where parents don't mind if their teenage kids have
sex—indeed, where it's normal for 14 year olds to become
mothers. So what's going on? There does seem to be a universal
taboo against sex with prepubescent children. One can imagine
evolutionary reasons for that. And I think this is the main reason
parents in industrialized societies dislike teenage kids having
sex. They still think of them as children, even though biologically
they're not, so the taboo against child sex still has force.One thing adults conceal about sex they also conceal about drugs:
that it can cause great pleasure. That's what makes sex and drugs
so dangerous. The desire for them can cloud one's judgement—which
is especially frightening when the judgement being clouded is the
already wretched judgement of a teenage kid.Here parents' desires conflict. Older societies told kids they had
bad judgement, but modern parents want their children to be confident.
This may well be a better plan than the old one of putting them in
their place, but it has the side effect that after having implicitly
lied to kids about how good their judgement is, we then have to lie
again about all the things they might get into trouble with if they
believed us.If parents told their kids the truth about sex and drugs, it would
be: the reason you should avoid these things is that you have lousy
judgement. People with twice your experience still get burned by
them. But this may be one of those cases where the truth wouldn't
be convincing, because one of the symptoms of bad judgement is
believing you have good judgement. When you're too weak to lift
something, you can tell, but when you're making a decision impetuously,
you're all the more sure of it.
InnocenceAnother reason parents don't want their kids having sex is that
they want to keep them innocent. Adults have a certain model of
how kids are supposed to behave, and it's different from what they
expect of other adults.One of the most obvious differences is the words kids are allowed
to use. Most parents use words when talking to other adults that
they wouldn't want their kids using. They try to hide even the
existence of these words for as long as they can. And this is
another of those conspiracies everyone participates in: everyone
knows you're not supposed to swear in front of kids.I've never heard more different explanations for anything parents
tell kids than why they shouldn't swear. Every parent I know forbids
their children to swear, and yet no two of them have the same
justification. It's clear most start with not wanting kids to
swear, then make up the reason afterward.So my theory about what's going on is that the function of
swearwords is to mark the speaker as an adult. There's no difference
in the meaning of "shit" and "poopoo." So why should one be ok for
kids to say and one forbidden? The only explanation is: by definition.
[3]Why does it bother adults so much when kids do things reserved for
adults? The idea of a foul-mouthed, cynical 10 year old leaning
against a lamppost with a cigarette hanging out of the corner of
his mouth is very disconcerting. But why?One reason we want kids to be innocent is that we're programmed to
like certain kinds of helplessness. I've several times heard mothers
say they deliberately refrained from correcting their young children's
mispronunciations because they were so cute. And if you think about
it, cuteness is helplessness. Toys and cartoon characters meant to
be cute always have clueless expressions and stubby, ineffectual
limbs.It's not surprising we'd have an inborn desire to love and protect
helpless creatures, considering human offspring are so helpless for
so long. Without the helplessness that makes kids cute, they'd be
very annoying. They'd merely seem like incompetent adults. But
there's more to it than that. The reason our hypothetical jaded
10 year old bothers me so much is not just that he'd be annoying,
but that he'd have cut off his prospects for growth so early. To
be jaded you have to think you know how the world works, and any
theory a 10 year old had about that would probably be a pretty
narrow one.Innocence is also open-mindedness. We want kids to be innocent so
they can continue to learn. Paradoxical as it sounds, there are
some kinds of knowledge that get in the way of other kinds of
knowledge. If you're going to learn that the world is a brutal
place full of people trying to take advantage of one another, you're
better off learning it last. Otherwise you won't bother learning
much more.Very smart adults often seem unusually innocent, and I don't think
this is a coincidence. I think they've deliberately avoided learning
about certain things. Certainly I do. I used to think I wanted
to know everything. Now I know I don't.
DeathAfter sex, death is the topic adults lie most conspicuously about
to kids. Sex I believe they conceal because of deep taboos. But
why do we conceal death from kids? Probably because small children
are particularly horrified by it. They want to feel safe, and death
is the ultimate threat.One of the most spectacular lies our parents told us was about the
death of our first cat. Over the years, as we asked for more
details, they were compelled to invent more, so the story grew quite
elaborate. The cat had died at the vet's office. Of what? Of the
anaesthesia itself. Why was the cat at the vet's office? To be
fixed. And why had such a routine operation killed it? It wasn't
the vet's fault; the cat had a congenitally weak heart; the anaesthesia
was too much for it; but there was no way anyone could have
known this in advance. It was not till we were in our twenties
that the truth came out: my sister, then about three, had accidentally
stepped on the cat and broken its back.They didn't feel the need to tell us the cat was now happily in cat
heaven. My parents never claimed that people or animals who died
had "gone to a better place," or that we'd meet them again. It
didn't seem to harm us.My grandmother told us an edited version of the death of my
grandfather. She said they'd been sitting reading one day, and
when she said something to him, he didn't answer. He seemed to be
asleep, but when she tried to rouse him, she couldn't. "He was
gone." Having a heart attack sounded like falling asleep. Later I
learned it hadn't been so neat, and the heart attack had taken most
of a day to kill him.Along with such outright lies, there must have been a lot of changing
the subject when death came up. I can't remember that, of course,
but I can infer it from the fact that I didn't really grasp I was
going to die till I was about 19. How could I have missed something
so obvious for so long? Now that I've seen parents managing the
subject, I can see how: questions about death are gently but firmly
turned aside.On this topic, especially, they're met half-way by kids. Kids often
want to be lied to. They want to believe they're living in a
comfortable, safe world as much as their parents want them to believe
it.
[4]
IdentitySome parents feel a strong adherence to an ethnic or religious group
and want their kids to feel it too. This usually requires two
different kinds of lying: the first is to tell the child that he
or she is an X, and the second is whatever specific lies Xes
differentiate themselves by believing.
[5]Telling a child they have a particular ethnic or religious identity
is one of the stickiest things you can tell them. Almost anything
else you tell a kid, they can change their mind about later when
they start to think for themselves. But if you tell a kid they're
a member of a certain group, that seems nearly impossible to shake.This despite the fact that it can be one of the most premeditated
lies parents tell. When parents are of different religions, they'll
often agree between themselves that their children will be "raised
as Xes." And it works. The kids obligingly grow up considering
themselves as Xes, despite the fact that if their parents had chosen
the other way, they'd have grown up considering themselves as Ys.One reason this works so well is the second kind of lie involved.
The truth is common property. You can't distinguish your group by
doing things that are rational, and believing things that are true.
If you want to set yourself apart from other people, you have to
do things that are arbitrary, and believe things that are false.
And after having spent their whole lives doing things that are arbitrary
and believing things that are false, and being regarded as odd by
"outsiders" on that account, the cognitive dissonance pushing
children to regard themselves as Xes must be enormous. If they
aren't an X, why are they attached to all these arbitrary beliefs
and customs? If they aren't an X, why do all the non-Xes call them
one?This form of lie is not without its uses. You can use it to carry
a payload of beneficial beliefs, and they will also become part of
the child's identity. You can tell the child that in addition to
never wearing the color yellow, believing the world was created by
a giant rabbit, and always snapping their fingers before eating
fish, Xes are also particularly honest and industrious. Then X
children will grow up feeling it's part of their identity to be
honest and industrious.This probably accounts for a lot of the spread of modern religions,
and explains why their doctrines are a combination of the useful
and the bizarre. The bizarre half is what makes the religion stick,
and the useful half is the payload.
[6]
AuthorityOne of the least excusable reasons adults lie to kids is to maintain
power over them. Sometimes these lies are truly sinister, like a
child molester telling his victims they'll get in trouble if they
tell anyone what happened to them. Others seem more innocent; it
depends how badly adults lie to maintain their power, and what they
use it for.Most adults make some effort to conceal their flaws from children.
Usually their motives are mixed. For example, a father who has an
affair generally conceals it from his children. His motive is
partly that it would worry them, partly that this would introduce
the topic of sex, and partly (a larger part than he would admit)
that he doesn't want to tarnish himself in their eyes.If you want to learn what lies are told to kids, read almost any
book written to teach them about "issues."
[7]
<NAME> wrote
one called Why Are We Getting a Divorce? It begins with the three
most important things to remember about divorce, one of which is:
You shouldn't put the blame on one parent, because divorce is
never only one person's fault.
[8]
Really? When a man runs off with his secretary, is it always partly
his wife's fault? But I can see why Mayle might have said this.
Maybe it's more important for kids to respect their parents than
to know the truth about them.But because adults conceal their flaws, and at the same time insist
on high standards of behavior for kids, a lot of kids grow up feeling
they fall hopelessly short. They walk around feeling horribly evil
for having used a swearword, while in fact most of the adults around
them are doing much worse things.This happens in intellectual as well as moral questions. The more
confident people are, the more willing they seem to be to answer a
question "I don't know." Less confident people feel they have to
have an answer or they'll look bad. My parents were pretty good
about admitting when they didn't know things, but I must have been
told a lot of lies of this type by teachers, because I rarely heard
a teacher say "I don't know" till I got to college. I remember
because it was so surprising to hear someone say that in front of
a class.The first hint I had that teachers weren't omniscient came in sixth
grade, after my father contradicted something I'd learned in school.
When I protested that the teacher had said the opposite, my father
replied that the guy had no idea what he was talking about—that
he was just an elementary school teacher, after all.Just a teacher? The phrase seemed almost grammatically ill-formed.
Didn't teachers know everything about the subjects they taught?
And if not, why were they the ones teaching us?The sad fact is, US public school teachers don't generally understand
the stuff they're teaching very well. There are some sterling
exceptions, but as a rule people planning to go into teaching rank
academically near the bottom of the college population. So the
fact that I still thought at age 11 that teachers were infallible
shows what a job the system must have done on my brain.
SchoolWhat kids get taught in school is a complex mix of lies. The most
excusable are those told to simplify ideas to make them easy to
learn. The problem is, a lot of propaganda gets slipped into the
curriculum in the name of simplification.Public school textbooks represent a compromise between what various
powerful groups want kids to be told. The lies are rarely overt.
Usually they consist either of omissions or of over-emphasizing
certain topics at the expense of others. The view of history we
got in elementary school was a crude hagiography, with at least one
representative of each powerful group.The famous scientists I remember were Einstein, <NAME>, and
<NAME>. Einstein was a big deal because his
work led to the atom bomb. <NAME> was involved with X-rays.
But I was mystified about Carver. He seemed to have done stuff
with peanuts.It's obvious now that he was on the list because he was black (and
for that matter that <NAME> was on it because she was a woman),
but as a kid I was confused for years about him. I wonder if it
wouldn't have been better just to tell us the truth: that there
weren't any famous black scientists. Ranking George Washington
Carver with Einstein misled us not only about science, but about
the obstacles blacks faced in his time.As subjects got softer, the lies got more frequent. By the time
you got to politics and recent history, what we were taught was
pretty much pure propaganda. For example, we were taught to regard
political leaders as saints—especially the recently martyred
Kennedy and King. It was astonishing to learn later that they'd
both been serial womanizers, and that Kennedy was a speed freak to
boot. (By the time King's plagiarism emerged, I'd lost the ability
to be surprised by the misdeeds of famous people.)I doubt you could teach kids recent history without teaching them
lies, because practically everyone who has anything to say about
it has some kind of spin to put on it. Much recent history consists
of spin. It would probably be better just to teach them metafacts
like that.Probably the biggest lie told in schools, though, is that the way
to succeed is through following "the rules." In fact most such
rules are just hacks to manage large groups efficiently.
PeaceOf all the reasons we lie to kids, the most powerful is probably
the same mundane reason they lie to us.Often when we lie to people it's not part of any conscious strategy,
but because they'd react violently to the truth. Kids, almost by
definition, lack self-control. They react violently to things—and
so they get lied to a lot.
[9]A few Thanksgivings ago, a friend of mine found himself in a situation
that perfectly illustrates the complex motives we have when we lie
to kids. As the roast turkey appeared on the table, his alarmingly
perceptive 5 year old son suddenly asked if the turkey had wanted
to die. Foreseeing disaster, my friend and his wife rapidly
improvised: yes, the turkey had wanted to die, and in fact had lived
its whole life with the aim of being their Thanksgiving dinner.
And that (phew) was the end of that.Whenever we lie to kids to protect them, we're usually also lying
to keep the peace.One consequence of this sort of calming lie is that we grow up
thinking horrible things are normal. It's hard for us to feel a
sense of urgency as adults over something we've literally been
trained not to worry about. When I was about 10 I saw a documentary
on pollution that put me into a panic. It seemed the planet was
being irretrievably ruined. I went to my mother afterward to ask
if this was so. I don't remember what she said, but she made me
feel better, so I stopped worrying about it.That was probably the best way to handle a frightened 10 year old.
But we should understand the price. This sort of lie is one of the
main reasons bad things persist: we're all trained to ignore them.
DetoxA sprinter in a race almost immediately enters a state called "oxygen
debt." His body switches to an emergency source of energy that's
faster than regular aerobic respiration. But this process builds
up waste products that ultimately require extra oxygen to break
down, so at the end of the race he has to stop and pant for a while
to recover.We arrive at adulthood with a kind of truth debt. We were told a
lot of lies to get us (and our parents) through our childhood. Some
may have been necessary. Some probably weren't. But we all arrive
at adulthood with heads full of lies.There's never a point where the adults sit you down and explain all
the lies they told you. They've forgotten most of them. So if
you're going to clear these lies out of your head, you're going to
have to do it yourself.Few do. Most people go through life with bits of packing material
adhering to their minds and never know it. You probably never can
completely undo the effects of lies you were told as a kid, but
it's worth trying. I've found that whenever I've been able to undo
a lie I was told, a lot of other things fell into place.Fortunately, once you arrive at adulthood you get a valuable new
resource you can use to figure out what lies you were told. You're
now one of the liars. You get to watch behind the scenes as adults
spin the world for the next generation of kids.The first step in clearing your head is to realize how far you are
from a neutral observer. When I left high school I was, I thought,
a complete skeptic. I'd realized high school was crap. I thought
I was ready to question everything I knew. But among the many other
things I was ignorant of was how much debris there already was in
my head. It's not enough to consider your mind a blank slate. You
have to consciously erase it.
Notes[1]
One reason I stuck with such a brutally simple word is that
the lies we tell kids are probably not quite as harmless as we
think. If you look at what adults told children in the past, it's
shocking how much they lied to them. Like us, they did it with the
best intentions. So if we think we're as open as one could reasonably
be with children, we're probably fooling ourselves. Odds are people
in 100 years will be as shocked at some of the lies we tell as we
are at some of the lies people told 100 years ago.I can't predict which these will be, and I don't want to write an
essay that will seem dumb in 100 years. So instead of using special
euphemisms for lies that seem excusable according to present fashions,
I'm just going to call all our lies lies.(I have omitted one type: lies told to play games with kids'
credulity. These range from "make-believe," which is not really a
lie because it's told with a wink, to the frightening lies told by
older siblings. There's not much to say about these: I wouldn't
want the first type to go away, and wouldn't expect the second type
to.)[2]
Calaprice, Alice (ed.), The Quotable Einstein, Princeton
University Press, 1996.[3]
If you ask parents why kids shouldn't swear, the less educated
ones usually reply with some question-begging answer like "it's
inappropriate," while the more educated ones come up with elaborate
rationalizations. In fact the less educated parents seem closer
to the truth.[4]
As a friend with small children pointed out, it's easy for small
children to consider themselves immortal, because time seems to
pass so slowly for them. To a 3 year old, a day feels like a month
might to an adult. So 80 years sounds to him like 2400 years would
to us.[5]
I realize I'm going to get endless grief for classifying religion
as a type of lie. Usually people skirt that issue with some
equivocation implying that lies believed for a sufficiently long
time by sufficiently large numbers of people are immune to the usual
standards for truth. But because I can't predict which lies future
generations will consider inexcusable, I can't safely omit any type
we tell. Yes, it seems unlikely that religion will be out of fashion
in 100 years, but no more unlikely than it would have seemed to
someone in 1880 that schoolchildren in 1980 would be taught that
masturbation was perfectly normal and not to feel guilty about it.[6]
Unfortunately the payload can consist of bad customs as well
as good ones. For example, there are certain qualities that some
groups in America consider "acting white." In fact most of them
could as accurately be called "acting Japanese." There's nothing
specifically white about such customs. They're common to all cultures
with long traditions of living in cities. So it is probably a
losing bet for a group to consider behaving the opposite way as
part of its identity.[7]
In this context, "issues" basically means "things we're going
to lie to them about." That's why there's a special name for these
topics.[8]
Mayle, Peter, Why Are We Getting a Divorce?, Harmony, 1988.[9]
The ironic thing is, this is also the main reason kids lie to
adults. If you freak out when people tell you alarming things,
they won't tell you them. Teenagers don't tell their parents what
happened that night they were supposed to be staying at a friend's
house for the same reason parents don't tell 5 year olds the truth
about the Thanksgiving turkey. They'd freak if they knew.
Thanks to <NAME>, <NAME>, <NAME>,
<NAME>, <NAME>, <NAME>, <NAME>, and <NAME> for reading drafts of this. And since there
are some controversial ideas here, I should add that none of them
agreed with everything in it.German TranslationFrench TranslationRussian Translation
|
|
https://github.com/horaoen/typstempl | https://raw.githubusercontent.com/horaoen/typstempl/master/demo/cosheet.typ | typst | mport "cosheet.typ": cosheet
#show: doc => cosheet(
doc
)
= 去除各种空格
```java
public String trim(String str) {
// "\u0020" 半角空格, office空格, 全角空格
return str.trim().replace("\u00a0", "").replace("\u3000", "");
}
```
== simple trim
`str.trim()`
== test font
`true == 1`
|
|
https://github.com/tingerrr/hydra | https://raw.githubusercontent.com/tingerrr/hydra/main/tests/features/use-last/multiple-ancestors/test.typ | typst | MIT License | // Synopsis:
// - When there are multiple ancestors on one page hydra should still show the last heading
#import "/src/lib.typ": hydra
#set page(
paper: "a7",
header: context hydra(2, use-last: true),
)
#set heading(numbering: "1.1")
#set par(justify: true)
= Introduction
== First Section
#lorem(50)
== Second Section
#lorem(100)
== Third section
#lorem(50)
= Other
#lorem(10)
== test
#lorem(10)
= More
#lorem(5)
== more tests
#lorem(10)
|
https://github.com/Otto-AA/definitely-not-tuw-thesis | https://raw.githubusercontent.com/Otto-AA/definitely-not-tuw-thesis/main/src/utils.typ | typst | MIT No Attribution | #let name-with-titles = p => {
if "pre-title" in p {
[#p.at("pre-title", default: "") ]
}
p.at("name", default: "")
if "post-title" in p {
[ #p.at("post-title", default: "")]
}
} |
https://github.com/VisualFP/docs | https://raw.githubusercontent.com/VisualFP/docs/main/SA/design_concept/content/introduction/tool_research/flo.typ | typst | = flo <flo>
flo is a visual and functional programming language. It features a programming
environment based on blocks connected using cables, as shown in
@flo_screenshot_1. The corresponding compiler converts the visual
arrangements and connections into Haskell code.
#figure(
image("../../../static/flo_screenshot_1.png", width: 50%),
caption: [Screenshot of an if function definition in flo @flo-manual]) <flo_screenshot_1>
A block's parameters and outputs are represented by sockets, which can be
connected to compatible sockets through click-and-drag. The compiler can infer
the sockets' types and reject incompatible connections.
A specialty of flo is that blocks represent values and types.
A type block is either a basic type, such as `Int` or `Bool`, or a constructor
to a complex type with type parameters, represented through sockets. An
example of a type being used as type parameter is shown in @flo_screenshot_2.
#figure(
image("../../../static/flo_screenshot_2.png", width: 30%),
caption: [Screenshot of a negation function application in flo @flo-manual]) <flo_screenshot_2>
flo was a research project and has not been actively developed since 2016.
Out of all researched tools, it is probably the one that comes closest to
VisualFP in terms of its goals.
|
|
https://github.com/FuryMartin/fury-note-typst | https://raw.githubusercontent.com/FuryMartin/fury-note-typst/master/README.md | markdown | MIT License | # simple-typst-note
## Usage
```rust
#import "lib.typ": *
#let title = "Hello, World!"
#let author = (
name: "<NAME>",
email: "<EMAIL>"
)
#let bib = bibliography("refer.bib")
#show: note.with(
title: [#title],
author: author,
bib:bib,
lang: "zh",
toc: false,
)
= Introduction
#lorem(50)
```
## Requirements
- Install `Family Song` for better font effect. You can visit [Keldos-Li/typora-latex-theme-fonts](https://github.com/Keldos-Li/typora-latex-theme-fonts/tree/main) for more infomation.
## Advices
- Edit with VSCode + [tynymist-typst](https://marketplace.visualstudio.com/items?itemName=myriad-dreamin.tinymist) is recommended for writing typst notes.
- Convert to docx using [Pandoc](https://pandoc.org/) with `pandoc main.typ -o main.docx --reference-doc template.docx`

|
https://github.com/Many5900/aau-typst | https://raw.githubusercontent.com/Many5900/aau-typst/main/main.typ | typst | #import "custom.typ": *
#import "template.typ": *
#import "@preview/codly:1.0.0": *
#show: codly-init.with()
// Take a look at the file `template.typ` in the file panel
// to customize this template and discover how it works.
#show: project.with(
meta: (
title: "AAU Project Report Name",
theme: "Insert theme name",
project_period: "Fall Semester 2024",
project_group: "cs-24-sw-3-xx",
participants: (
(name: "...", email: <EMAIL>"),
(name: "...", email: <EMAIL>"),
(name: "...", email: <EMAIL>"),
(name: "...", email: <EMAIL>"),
(name: "...", email: <EMAIL>"),
(name: "...", email: <EMAIL>"),
(name: "...", email: <EMAIL>"),
),
supervisor: (
(name: "Supervisor 1", email: "<EMAIL>"),
),
date: datetime.today().display()
),
// Insert your abstract after the colon, wrapped in brackets.
// Example: `abstract: [This is my abstract...]`
abstract: [This is the abstract, please write something here. #lorem(59)],
department: "Computer Science",
)
// This is the primary file in the project.
// Commonly referred to as 'master' in LaTeX, and wokenly called 'main' in Typst.
// Todo list
#outline(title: "TODOs", target: figure.where(kind: "todo"))
#include "chapters/chapter1.typ"
#pagebreak(weak: true)
#include "chapters/chapter2.typ"
#pagebreak(weak: true)
#include "chapters/components.typ"
#pagebreak(weak: true)
#bibliography("sources/sources1.bib") |
|
https://github.com/bigskysoftware/hypermedia-systems-book | https://raw.githubusercontent.com/bigskysoftware/hypermedia-systems-book/main/ch14-conclusion.typ | typst | Other | #import "lib/definitions.typ": *
== Conclusion
We hope to have convinced you that hypermedia, rather than being a
"legacy" technology or a technology only appropriate for "documents" of links,
text and pictures, is, in fact, a powerful technology for building _applications_.
In this book you have seen how to build sophisticated user interfaces --- for
both the web, with htmx, and for mobile applications, using Hyperview --- using
hypermedia as a core underlying application technology.
Many web developers view the links and forms of "plain" HTML as bygone tools
from a less sophisticated age. And, in some ways, they are right: there were
definite usability issues with the original web. However, there are now
JavaScript libraries that extend HTML by addressing its core limitations.
Htmx, for example, allowed us to:
- Make any element capable of issuing an HTTP request
- Make any event capable of triggering an HTTP event
- Use all the available types of HTTP methods
- Target any element in the DOM for replacement
With that, we were able to build user interfaces for Contact.app that many
developers would assume require a significant amount of client-side JavaScript,
and we did it using hypermedia concepts.
The Hypermedia-Driven Application approach is not right for every application.
For many applications, though, the increased flexibility and simplicity of
hypermedia can be a huge benefit. Even if your application wouldn’t benefit from
this approach, it is worthwhile to
_understand_ the approach, its strengths and weaknesses, and how it differs from
the approach you are taking. The original web grew faster than any distributed
system in history; web developers should know how to tap the power of the
underlying technologies that made that growth possible.
=== Pausing, and Reflecting <_pausing_and_reflecting>
The JavaScript community and, by extension, the web development community is
famously chaotic, with new frameworks and technologies emerging monthly, and
sometimes even _weekly_. It can be exhausting to keep up with the latest and
greatest technologies, and, at the same time, terrifying that we _won’t_ keep up
with them and be left behind in our career.
This is not a fear without foundation: there are many senior software engineers
that have seen their careers peter out because they picked a technology to
specialize in that, fairly or not, did not thrive. The web development world
tends to be young, with many companies favoring young developers over older
developers who "haven’t kept up."
We shouldn’t sugar-coat these realities of our industry. On the other hand, we
also shouldn’t ignore the downside that these realities create. It creates a
high-pressure environment where everyone is watching for
"the new new" thing, that is, for the latest and greatest technology that is
going to change everything. It creates pressure to _claim_
that your technology is going to change everything. It tends to favor
_sophistication_ over _simplicity_. People are scared to ask
"Is this too complex?" because it sounds an awful lot like "I’m not smart enough
to understand this."
The software industry tends, especially in web development, to lean far more
towards innovating, rather than understanding existing technologies and building
on them or within them. We tend to look ahead for new, genius solutions, rather
than looking to established ideas. This is understandable: the technology world
is necessarily a forward-looking industry.
On the other hand --- as we saw with Roy Fielding’s formulation of REST --- some
early architects of the web had some great ideas which have been overlooked. We
are old enough to have seen hypermedia come and go as the "new new" idea. It was
a little shocking to us to see powerful ideas like REST discarded so cavalierly
by the industry. Fortunately, the concepts are still sitting there, waiting to
be rediscovered and reinvigorated. The original, RESTful architecture of the
web, when looked at with fresh eyes, can address many of the problems that
today’s web developers are facing.
Perhaps, following <NAME>’s advice, it is time to pause and reflect.
Perhaps, for a few quiet moments, we can put the endless swirl of the
"new new" aside, look back on where the web came from, and learn.
Perhaps it’s time to give hypermedia a chance.
|
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/editors/vscode/Configuration.md | markdown | Apache License 2.0 | # Tinymist Server Configuration
## `tinymist.outputPath`
The path pattern to store Typst artifacts, you can use `$root` or `$dir` or `$name` to do magic configuration, e.g. `$dir/$name` (default) and `$root/target/$dir/$name`.
- **Type**: `string`
## `tinymist.exportPdf`
The extension can export PDFs of your Typst files. This setting controls whether this feature is enabled and how often it runs.
- **Type**: `string`
- **Enum**:
- `never`: Never export PDFs, you will manually run typst.
- `onSave`: Export PDFs when you save a file.
- `onType`: Export PDFs as you type in a file.
- `onDocumentHasTitle`: Export PDFs when a document has a title (and save a file), which is useful to filter out template files.
- **Default**: `"never"`
## `tinymist.rootPath`
Configure the root for absolute paths in typst. Hint: you can set the rootPath to `-`, so that tinymist will always use parent directory of the file as the root path. Note: for neovim users, if it complains root not found, you must set `require("lspconfig")["tinymist"].setup { root_dir }` as well, see [tinymist#528](https://github.com/Myriad-Dreamin/tinymist/issues/528).
- **Type**: `string` or `null`
## `tinymist.semanticTokens`
Enable or disable semantic tokens (LSP syntax highlighting)
- **Type**: `string`
- **Enum**:
- `enable`: Use semantic tokens for syntax highlighting
- `disable`: Do not use semantic tokens for syntax highlighting
- **Default**: `"enable"`
## `tinymist.onEnterEvent`
Enable or disable [experimental/onEnter](https://github.com/rust-lang/rust-analyzer/blob/master/docs/dev/lsp-extensions.md#on-enter) (LSP onEnter feature) to allow automatic insertion of characters on enter, such as `///` for comments. Note: restarting the editor is required to change this setting.
- **Type**: `boolean`
- **Default**: `true`
## `tinymist.systemFonts`
A flag that determines whether to load system fonts for Typst compiler, which is useful for ensuring reproducible compilation. If set to null or not set, the extension will use the default behavior of the Typst compiler. Note: You need to restart LSP to change this options.
- **Type**: `boolean`
- **Default**: `true`
## `tinymist.fontPaths`
A list of file or directory path to fonts. Note: The configuration source in higher priority will **override** the configuration source in lower priority. The order of precedence is: Configuration `tinymist.fontPaths` > Configuration `tinymist.typstExtraArgs.fontPaths` > LSP's CLI Argument `--font-path` > The environment variable `TYPST_FONT_PATHS` (a path list separated by `;` (on Windows) or `:` (Otherwise)). Note: If the path to fonts is a relative path, it will be resolved based on the root directory. Note: In VSCode, you can use VSCode variables in the path, e.g. `${workspaceFolder}/fonts`.
- **Type**: `array` or `null`
## `tinymist.compileStatus`
In VSCode, enable compile status meaning that the extension will show the compilation status in the status bar. Since Neovim and Helix don't have a such feature, it is disabled by default at the language server label.
- **Type**: `string`
- **Enum**:
- `enable`
- `disable`
- **Default**: `"enable"`
## `tinymist.typstExtraArgs`
You can pass any arguments as you like, and we will try to follow behaviors of the **same version** of typst-cli. Note: the arguments may be overridden by other settings. For example, `--font-path` will be overridden by `tinymist.fontPaths`.
- **Type**: `array`
- **Default**: `[]`
## `tinymist.serverPath`
The extension can use a local tinymist executable instead of the one bundled with the extension. This setting controls the path to the executable.
- **Type**: `string` or `null`
## `tinymist.trace.server`
Traces the communication between VS Code and the language server.
- **Type**: `string`
- **Enum**:
- `off`
- `messages`
- `verbose`
- **Default**: `"off"`
## `tinymist.formatterMode`
The extension can format Typst files using typstfmt or typstyle.
- **Type**: `string`
- **Enum**:
- `disable`: Formatter is not activated.
- `typstyle`: Use typstyle formatter.
- `typstfmt`: Use typstfmt formatter.
- **Default**: `"disable"`
## `tinymist.formatterPrintWidth`
Set the print width for the formatter, which is a **soft limit** of characters per line. See [the definition of *Print Width*](https://prettier.io/docs/en/options.html#print-width). Note: this has lower priority than the formatter's specific configurations.
- **Type**: `number`
- **Default**: `120`
## `tinymist.showExportFileIn`
Configures way of opening exported files, e.g. inside of editor tabs or using system application.
## `tinymist.dragAndDrop`
Whether to handle drag-and-drop of resources into the editing typst document. Note: restarting the editor is required to change this setting.
- **Type**: `string`
- **Enum**:
- `enable`
- `disable`
- **Default**: `"enable"`
## `tinymist.previewFeature`
Enable or disable preview features of Typst. Note: restarting the editor is required to change this setting.
- **Type**: `string`
- **Enum**:
- `enable`
- `disable`
- **Default**: `"enable"`
## `tinymist.preview.refresh`
Refresh preview when the document is saved or when the document is changed
- **Type**: `string`
- **Enum**:
- `onSave`: Refresh preview on save
- `onType`: Refresh preview on type
- **Default**: `"onType"`
## `tinymist.preview.scrollSync`
Configure scroll sync mode.
- **Type**: `string`
- **Enum**:
- `never`: Disable automatic scroll sync
- `onSelectionChangeByMouse`: Scroll preview to current cursor position when selection changes by mouse
- `onSelectionChange`: Scroll preview to current cursor position when selection changes by mouse or keyboard (any source)
- **Default**: `"onSelectionChangeByMouse"`
## `tinymist.preview.partialRendering`
Only render visible part of the document. This can improve performance but still being experimental.
- **Type**: `boolean`
- **Default**: `true`
## `tinymist.preview.invertColors`
Invert colors of the preview (useful for dark themes without cost). Please note you could see the origin colors when you hover elements in the preview. It is also possible to specify strategy to each element kind by an object map in JSON format.
## `tinymist.preview.cursorIndicator`
(Experimental) Show typst cursor indicator in preview.
- **Type**: `boolean`
|
https://github.com/Lucas-Wye/tech-note | https://raw.githubusercontent.com/Lucas-Wye/tech-note/main/src/gcc.typ | typst | = GCC
#label("gcc")
- GCC编译器也称为Linux
GCC命令,它有很多选项。GCC编译器是Linux下最常用的编译器。
== Install
#label("install")
```sh
# MacOS安装Xcode工具链
xcode-select --install
# Ubuntu
sudo apt install gcc
```
== Basic
#label("basic")
```sh
gcc -c filename.c # compile only, produce .o
gcc -g # compile for debugging
gcc -o filename.o #
gcc -O 1,2,3,4,s,fast # for optimization level
gcc -Ipathname
gcc -Dsymbol # define preprocessor symbol
gcc -Ldirectory # add directory to the library search path
gcc -lxyz # link with library libxyz.a or libxyz.so
```
== gdb
#label("gdb")
```sh
gdb BINARY_FILE
list
br 8 # breakpoint in line 8
run
print value
next
where
help
quit
```
== multiple gcc version in one Ubuntu machine
#label("multiple-gcc-version-in-one-ubuntu-machine")
use `update-alternatives` to manage them.
```sh
sudo update-alternatives --config gcc
```
== make
#label("make")
(1)Predefined Macros - AS - assembler (as) - CC - C compiler command
(cc) - FC - Fortran compiler command (fc) - CPP - C++ preprocessing
command (\$(CC) -E) - CXX - C++ compiler command (g++) - CFLAGS - C
compiler option flags (e.g. -g) - FFLAGS - Fortran compiler option flags
(e.g. -g) - LDFLAGS - Linking option flags (e.g. –L /usr/share/lib) -
LDLIBS – Linking libraries (e.g. -lm)
(2)Special Internal Macros
```sh
$* # The basename of the current target
$< # The name of a dependency file, as we see on last page
$@ # The name of the current target.
$? # The list of dependencies that are newer than the target.
```
== More
#label("more")
#link("https://blog.csdn.net/gatieme/article/details/51671430")[more of gdb]
\
#link("https://github.com/Lucas-Wye/Makefile-Templates")[Makefile example]
|
|
https://github.com/Doublonmousse/pandoc-typst-reproducer | https://raw.githubusercontent.com/Doublonmousse/pandoc-typst-reproducer/main/color_issues/hsv.typ | typst | #square(
fill: color.hsv(30deg, 50%, 60%)
)
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/fireside/1.0.0/.demo/demo_medium.typ | typst | Apache License 2.0 | #import "@preview/fireside:1.0.0": *
#show: fireside.with(
title: [Anakin \ Skywalker],
from-details: [
Appt. x, \
Mos Espa, \
Tatooine \
<EMAIL> \ +999 xxxx xxx
],
to-details: [
Sheev Palpatine \
500 Republica, \
Ambassadorial Sector, Senate District, \
Galactic City, \ Coruscant
],
)
Dear Emperor,
I'm applying for an internship in #lorem(100)
#lorem(80)
#lorem(95)
Sincerely,
Mr. Skywalker
|
https://github.com/The-Notebookinator/notebookinator | https://raw.githubusercontent.com/The-Notebookinator/notebookinator/main/entries.typ | typst | The Unlicense | #import "/globals.typ"
#import "./utils.typ"
#import "./themes/themes.typ"
/// The generic entry creation function. This function is not meant to be called by the user. Instead, use the three entry variants, frontmatter, body, and appendix, to create entries.
///
/// - section (string): The type of entry. Takes either "frontmatter", "body", or "appendix".
/// - title (string): The title of the entry.
/// - type (string): The type of entry. The possible values for this are decided by the theme.
/// - date (datetime): The date that the entry occured at.
/// - author (str): The author of the entry.
/// - witness (str): The witness of the entry.
/// - participants (array): The people who participated in the entry.
/// - body (content): The content of the entry.
#let create-entry(
section: none,
title: "",
type: none,
date: none,
author: "",
witness: "",
participants: (),
body,
) = {
let (state, entry-label) = if section == "frontmatter" {
(globals.frontmatter-entries, label("notebook-frontmatter"))
} else if section == "body" {
(globals.entries, label("notebook-body"))
} else if section == "appendix" {
(globals.appendix-entries, label("notebook-appendix"))
} else {
panic("No valid entry type selected")
}
state.update(entries => {
// Inject the proper labels and settings changes into the user's entry body
let final-body = if entries.len() == 0 {
[#counter(page).update(1)] // Correctly set the page number for each section
} + [
#metadata(none) #entry-label
#counter(footnote).update(0)
] + body // Place a label on blank content to the table of contents can find each entry
entries.push((
ctx: (
title: title,
type: type,
date: date,
author: author,
witness: witness,
participants: participants
),
body: final-body,
))
entries
})
}
/// Variant of the `#create-entry()` function that creates a frontmatter entry.
///
/// *Example Usage:*
///
/// ```typ
/// #create-frontmatter-entry(title: "Frontmatter")[
/// #lorem(50)
/// ]
/// ```
///
#let create-frontmatter-entry = create-entry.with(section: "frontmatter")
/// Variant of the `#create-entry()` function that creates a body entry.
///
/// *Example Usage:*
///
/// ```typ
/// #create-body-entry(
/// title: "Title",
/// date: datetime(year: 2024, month: 1, day: 1),
/// type: "identify", // Change this depending on what your theme allows
/// author: "Bobert",
/// witness: "Bobernius",
/// )[
/// #lorem(50)
/// ]
/// ```
#let create-body-entry = create-entry.with(section: "body")
/// Variant of the `#create-entry()` function that creates an appendix entry.
///
/// *Example Usage:*
///
/// ```typ
/// #create-appendix-entry(title: "Appendix")[
/// #lorem(50)
/// ]
/// ```
#let create-appendix-entry = create-entry.with(section: "appendix")
|
https://github.com/jomaway/typst-teacher-templates | https://raw.githubusercontent.com/jomaway/typst-teacher-templates/main/ttt-exam/lib/template.typ | typst | MIT License | #import "@preview/ttt-utils:0.1.2": assignments, components, grading, helpers
#import "i18n.typ": *
#import components: *
#import assignments: *
#import grading: *
#import "points.typ": *
#import "headers.typ": *
#let _appendix(body, title: auto, ..args) = [
#set page(footer: none, header:none, ..args.named())
#if-auto-then(title, heading(linguify("appendix", from: ling_db)))
#label("appendix")
#body
]
// The exam function defines how your document looks.
#let exam(
// metadata
logo: none,
title: "exam", // shoes the title of the exam -> 1. Schulaufgabe | Stegreifaufgabe | Kurzarbeit
subtitle: none,
date: none, // date of the exam
class: "",
subject: "" ,
authors: "",
// config
solution: auto, // auto | false | true
cover: false, // false | true
header: auto, // auto | false | true
eval-table: true,
appendix: none,
footer-msg: auto,
body
) = {
// Set the document's basic properties.
set document(author: authors, title: "exam-"+subject+"-"+class)
// set page properties
set page(
margin: (left: 20mm, right: 20mm, top: 20mm, bottom: 20mm),
footer: {
// Copyright symbol
sym.copyright;
// YEAR
if type(date) == datetime { date.display("[year]") } else { datetime.today().display("[year]") }
// Authors
if (type(authors) == array) [
#authors.join(", ", last: " and ")
] else [
#authors
]
h(1fr)
// Footer message: Default Good luck
if footer-msg == auto {
text(10pt, weight: "semibold", font: "Atma")[
#linguify("good_luck", from: ling_db) #box(height: 1em, image("assets/four-leaf-clover.svg"))
]
} else {
footer-msg
}
h(1fr)
// Page Counter
counter(page).display("1 / 1", both: true)
},
header: context if (counter(page).get().first() > 1) { box(stroke: ( 0.5pt), width: 100%, inset: 6pt)[ Name: ] },
)
// check cli input for solution
if solution == auto {
set-solution-mode(helpers.bool-input("solution"))
} else {
set-solution-mode(solution)
}
let cover-page = header-page(
logo: logo,
title,
subtitle: subtitle,
class,
subject,
date,
point-field: point-sum-box
)
let header-block = header-block(
title,
subtitle: subtitle ,
class,
subject,
date,
logo: logo
)
// Include Header-Block
if (cover) {
cover-page
} else if (header != false) {
header-block
}
// Predefined show rules
show par: set block(above: 1.2em, below: 1.2em)
// Content-Body
body
if not cover and eval-table {
align(bottom + end,block[
#set align(start)
*#ling("points"):* \
#point-sum-box
])
}
if appendix != none {
_appendix(appendix)
}
}
|
https://github.com/tingerrr/hydra | https://raw.githubusercontent.com/tingerrr/hydra/main/doc/examples/book/a.typ | typst | MIT License | #import "/doc/examples/template.typ": example
#show: example.with(book: false)
#include "content.typ"
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-A720.typ | typst | Apache License 2.0 | #let data = (
("MODIFIER LETTER STRESS AND HIGH TONE", "Sk", 0),
("MODIFIER LETTER STRESS AND LOW TONE", "Sk", 0),
("LATIN CAPITAL LETTER EGYPTOLOGICAL ALEF", "Lu", 0),
("LATIN SMALL LETTER EGYPTOLOGICAL ALEF", "Ll", 0),
("LATIN CAPITAL LETTER EGYPTOLOGICAL AIN", "Lu", 0),
("LATIN SMALL LETTER EGYPTOLOGICAL AIN", "Ll", 0),
("LATIN CAPITAL LETTER HENG", "Lu", 0),
("LATIN SMALL LETTER HENG", "Ll", 0),
("LATIN CAPITAL LETTER TZ", "Lu", 0),
("LATIN SMALL LETTER TZ", "Ll", 0),
("LATIN CAPITAL LETTER TRESILLO", "Lu", 0),
("LATIN SMALL LETTER TRESILLO", "Ll", 0),
("LATIN CAPITAL LETTER CUATRILLO", "Lu", 0),
("LATIN SMALL LETTER CUATRILLO", "Ll", 0),
("LATIN CAPITAL LETTER CUATRILLO WITH COMMA", "Lu", 0),
("LATIN SMALL LETTER CUATRILLO WITH COMMA", "Ll", 0),
("LATIN LETTER SMALL CAPITAL F", "Ll", 0),
("LATIN LETTER SMALL CAPITAL S", "Ll", 0),
("LATIN CAPITAL LETTER AA", "Lu", 0),
("LATIN SMALL LETTER AA", "Ll", 0),
("LATIN CAPITAL LETTER AO", "Lu", 0),
("LATIN SMALL LETTER AO", "Ll", 0),
("LATIN CAPITAL LETTER AU", "Lu", 0),
("LATIN SMALL LETTER AU", "Ll", 0),
("LATIN CAPITAL LETTER AV", "Lu", 0),
("LATIN SMALL LETTER AV", "Ll", 0),
("LATIN CAPITAL LETTER AV WITH HORIZONTAL BAR", "Lu", 0),
("LATIN SMALL LETTER AV WITH HORIZONTAL BAR", "Ll", 0),
("LATIN CAPITAL LETTER AY", "Lu", 0),
("LATIN SMALL LETTER AY", "Ll", 0),
("LATIN CAPITAL LETTER REVERSED C WITH DOT", "Lu", 0),
("LATIN SMALL LETTER REVERSED C WITH DOT", "Ll", 0),
("LATIN CAPITAL LETTER K WITH STROKE", "Lu", 0),
("LATIN SMALL LETTER K WITH STROKE", "Ll", 0),
("LATIN CAPITAL LETTER K WITH DIAGONAL STROKE", "Lu", 0),
("LATIN SMALL LETTER K WITH DIAGONAL STROKE", "Ll", 0),
("LATIN CAPITAL LETTER K WITH STROKE AND DIAGONAL STROKE", "Lu", 0),
("LATIN SMALL LETTER K WITH STROKE AND DIAGONAL STROKE", "Ll", 0),
("LATIN CAPITAL LETTER BROKEN L", "Lu", 0),
("LATIN SMALL LETTER BROKEN L", "Ll", 0),
("LATIN CAPITAL LETTER L WITH HIGH STROKE", "Lu", 0),
("LATIN SMALL LETTER L WITH HIGH STROKE", "Ll", 0),
("LATIN CAPITAL LETTER O WITH LONG STROKE OVERLAY", "Lu", 0),
("LATIN SMALL LETTER O WITH LONG STROKE OVERLAY", "Ll", 0),
("LATIN CAPITAL LETTER O WITH LOOP", "Lu", 0),
("LATIN SMALL LETTER O WITH LOOP", "Ll", 0),
("LATIN CAPITAL LETTER OO", "Lu", 0),
("LATIN SMALL LETTER OO", "Ll", 0),
("LATIN CAPITAL LETTER P WITH STROKE THROUGH DESCENDER", "Lu", 0),
("LATIN SMALL LETTER P WITH STROKE THROUGH DESCENDER", "Ll", 0),
("LATIN CAPITAL LETTER P WITH FLOURISH", "Lu", 0),
("LATIN SMALL LETTER P WITH FLOURISH", "Ll", 0),
("LATIN CAPITAL LETTER P WITH SQUIRREL TAIL", "Lu", 0),
("LATIN SMALL LETTER P WITH SQUIRREL TAIL", "Ll", 0),
("LATIN CAPITAL LETTER Q WITH STROKE THROUGH DESCENDER", "Lu", 0),
("LATIN SMALL LETTER Q WITH STROKE THROUGH DESCENDER", "Ll", 0),
("LATIN CAPITAL LETTER Q WITH DIAGONAL STROKE", "Lu", 0),
("LATIN SMALL LETTER Q WITH DIAGONAL STROKE", "Ll", 0),
("LATIN CAPITAL LETTER R ROTUNDA", "Lu", 0),
("LATIN SMALL LETTER R ROTUNDA", "Ll", 0),
("LATIN CAPITAL LETTER RUM ROTUNDA", "Lu", 0),
("LATIN SMALL LETTER RUM ROTUNDA", "Ll", 0),
("LATIN CAPITAL LETTER V WITH DIAGONAL STROKE", "Lu", 0),
("LATIN SMALL LETTER V WITH DIAGONAL STROKE", "Ll", 0),
("LATIN CAPITAL LETTER VY", "Lu", 0),
("LATIN SMALL LETTER VY", "Ll", 0),
("LATIN CAPITAL LETTER VISIGOTHIC Z", "Lu", 0),
("LATIN SMALL LETTER VISIGOTHIC Z", "Ll", 0),
("LATIN CAPITAL LETTER THORN WITH STROKE", "Lu", 0),
("LATIN SMALL LETTER THORN WITH STROKE", "Ll", 0),
("LATIN CAPITAL LETTER THORN WITH STROKE THROUGH DESCENDER", "Lu", 0),
("LATIN SMALL LETTER THORN WITH STROKE THROUGH DESCENDER", "Ll", 0),
("LATIN CAPITAL LETTER VEND", "Lu", 0),
("LATIN SMALL LETTER VEND", "Ll", 0),
("LATIN CAPITAL LETTER ET", "Lu", 0),
("LATIN SMALL LETTER ET", "Ll", 0),
("LATIN CAPITAL LETTER IS", "Lu", 0),
("LATIN SMALL LETTER IS", "Ll", 0),
("LATIN CAPITAL LETTER CON", "Lu", 0),
("LATIN SMALL LETTER CON", "Ll", 0),
("MODIFIER LETTER US", "Lm", 0),
("LATIN SMALL LETTER DUM", "Ll", 0),
("LATIN SMALL LETTER LUM", "Ll", 0),
("LATIN SMALL LETTER MUM", "Ll", 0),
("LATIN SMALL LETTER NUM", "Ll", 0),
("LATIN SMALL LETTER RUM", "Ll", 0),
("LATIN LETTER SMALL CAPITAL RUM", "Ll", 0),
("LATIN SMALL LETTER TUM", "Ll", 0),
("LATIN SMALL LETTER UM", "Ll", 0),
("LATIN CAPITAL LETTER INSULAR D", "Lu", 0),
("LATIN SMALL LETTER INSULAR D", "Ll", 0),
("LATIN CAPITAL LETTER INSULAR F", "Lu", 0),
("LATIN SMALL LETTER INSULAR F", "Ll", 0),
("LATIN CAPITAL LETTER INSULAR G", "Lu", 0),
("LATIN CAPITAL LETTER TURNED INSULAR G", "Lu", 0),
("LATIN SMALL LETTER TURNED INSULAR G", "Ll", 0),
("LATIN CAPITAL LETTER TURNED L", "Lu", 0),
("LATIN SMALL LETTER TURNED L", "Ll", 0),
("LATIN CAPITAL LETTER INSULAR R", "Lu", 0),
("LATIN SMALL LETTER INSULAR R", "Ll", 0),
("LATIN CAPITAL LETTER INSULAR S", "Lu", 0),
("LATIN SMALL LETTER INSULAR S", "Ll", 0),
("LATIN CAPITAL LETTER INSULAR T", "Lu", 0),
("LATIN SMALL LETTER INSULAR T", "Ll", 0),
("MODIFIER LETTER LOW CIRCUMFLEX ACCENT", "Lm", 0),
("MODIFIER LETTER COLON", "Sk", 0),
("MODIFIER LETTER SHORT EQUALS SIGN", "Sk", 0),
("LATIN CAPITAL LETTER SALTILLO", "Lu", 0),
("LATIN SMALL LETTER SALTILLO", "Ll", 0),
("LATIN CAPITAL LETTER TURNED H", "Lu", 0),
("LATIN SMALL LETTER L WITH RETROFLEX HOOK AND BELT", "Ll", 0),
("LATIN LETTER SINOLOGICAL DOT", "Lo", 0),
("LATIN CAPITAL LETTER N WITH DESCENDER", "Lu", 0),
("LATIN SMALL LETTER N WITH DESCENDER", "Ll", 0),
("LATIN CAPITAL LETTER C WITH BAR", "Lu", 0),
("LATIN SMALL LETTER C WITH BAR", "Ll", 0),
("LATIN SMALL LETTER C WITH PALATAL HOOK", "Ll", 0),
("LATIN SMALL LETTER H WITH PALATAL HOOK", "Ll", 0),
("LATIN CAPITAL LETTER B WITH FLOURISH", "Lu", 0),
("LATIN SMALL LETTER B WITH FLOURISH", "Ll", 0),
("LATIN CAPITAL LETTER F WITH STROKE", "Lu", 0),
("LATIN SMALL LETTER F WITH STROKE", "Ll", 0),
("LATIN CAPITAL LETTER VOLAPUK AE", "Lu", 0),
("LATIN SMALL LETTER VOLAPUK AE", "Ll", 0),
("LATIN CAPITAL LETTER VOLAPUK OE", "Lu", 0),
("LATIN SMALL LETTER VOLAPUK OE", "Ll", 0),
("LATIN CAPITAL LETTER VOLAPUK UE", "Lu", 0),
("LATIN SMALL LETTER VOLAPUK UE", "Ll", 0),
("LATIN CAPITAL LETTER G WITH OBLIQUE STROKE", "Lu", 0),
("LATIN SMALL LETTER G WITH OBLIQUE STROKE", "Ll", 0),
("LATIN CAPITAL LETTER K WITH OBLIQUE STROKE", "Lu", 0),
("LATIN SMALL LETTER K WITH OBLIQUE STROKE", "Ll", 0),
("LATIN CAPITAL LETTER N WITH OBLIQUE STROKE", "Lu", 0),
("LATIN SMALL LETTER N WITH OBLIQUE STROKE", "Ll", 0),
("LATIN CAPITAL LETTER R WITH OBLIQUE STROKE", "Lu", 0),
("LATIN SMALL LETTER R WITH OBLIQUE STROKE", "Ll", 0),
("LATIN CAPITAL LETTER S WITH OBLIQUE STROKE", "Lu", 0),
("LATIN SMALL LETTER S WITH OBLIQUE STROKE", "Ll", 0),
("LATIN CAPITAL LETTER H WITH HOOK", "Lu", 0),
("LATIN CAPITAL LETTER REVERSED OPEN E", "Lu", 0),
("LATIN CAPITAL LETTER SCRIPT G", "Lu", 0),
("LATIN CAPITAL LETTER L WITH BELT", "Lu", 0),
("LATIN CAPITAL LETTER SMALL CAPITAL I", "Lu", 0),
("LATIN LETTER SMALL CAPITAL Q", "Ll", 0),
("LATIN CAPITAL LETTER TURNED K", "Lu", 0),
("LATIN CAPITAL LETTER TURNED T", "Lu", 0),
("LATIN CAPITAL LETTER J WITH CROSSED-TAIL", "Lu", 0),
("LATIN CAPITAL LETTER CHI", "Lu", 0),
("LATIN CAPITAL LETTER BETA", "Lu", 0),
("LATIN SMALL LETTER BETA", "Ll", 0),
("LATIN CAPITAL LETTER OMEGA", "Lu", 0),
("LATIN SMALL LETTER OMEGA", "Ll", 0),
("LATIN CAPITAL LETTER U WITH STROKE", "Lu", 0),
("LATIN SMALL LETTER U WITH STROKE", "Ll", 0),
("LATIN CAPITAL LETTER GLOTTAL A", "Lu", 0),
("LATIN SMALL LETTER GLOTTAL A", "Ll", 0),
("LATIN CAPITAL LETTER GLOTTAL I", "Lu", 0),
("LATIN SMALL LETTER GLOTTAL I", "Ll", 0),
("LATIN CAPITAL LETTER GLOTTAL U", "Lu", 0),
("LATIN SMALL LETTER GLOTTAL U", "Ll", 0),
("LATIN CAPITAL LETTER OLD POLISH O", "Lu", 0),
("LATIN SMALL LETTER OLD POLISH O", "Ll", 0),
("LATIN CAPITAL LETTER ANGLICANA W", "Lu", 0),
("LATIN SMALL LETTER ANGLICANA W", "Ll", 0),
("LATIN CAPITAL LETTER C WITH PALATAL HOOK", "Lu", 0),
("LATIN CAPITAL LETTER S WITH HOOK", "Lu", 0),
("LATIN CAPITAL LETTER Z WITH PALATAL HOOK", "Lu", 0),
("LATIN CAPITAL LETTER D WITH SHORT STROKE OVERLAY", "Lu", 0),
("LATIN SMALL LETTER D WITH SHORT STROKE OVERLAY", "Ll", 0),
("LATIN CAPITAL LETTER S WITH SHORT STROKE OVERLAY", "Lu", 0),
("LATIN SMALL LETTER S WITH SHORT STROKE OVERLAY", "Ll", 0),
("LATIN CAPITAL LETTER RAMS HORN", "Lu", 0),
("LATIN CAPITAL LETTER S WITH DIAGONAL STROKE", "Lu", 0),
("LATIN SMALL LETTER S WITH DIAGONAL STROKE", "Ll", 0),
(),
(),
("LATIN CAPITAL LETTER CLOSED INSULAR G", "Lu", 0),
("LATIN SMALL LETTER CLOSED INSULAR G", "Ll", 0),
(),
("LATIN SMALL LETTER DOUBLE THORN", "Ll", 0),
(),
("LATIN SMALL LETTER DOUBLE WYNN", "Ll", 0),
("LATIN CAPITAL LETTER MIDDLE SCOTS S", "Lu", 0),
("LATIN SMALL LETTER MIDDLE SCOTS S", "Ll", 0),
("LATIN CAPITAL LETTER SIGMOID S", "Lu", 0),
("LATIN SMALL LETTER SIGMOID S", "Ll", 0),
("LATIN CAPITAL LETTER LAMBDA", "Lu", 0),
("LATIN SMALL LETTER LAMBDA", "Ll", 0),
("LATIN CAPITAL LETTER LAMBDA WITH STROKE", "Lu", 0),
(),
(),
(),
(),
(),
(),
(),
(),
(),
(),
(),
(),
(),
(),
(),
(),
(),
(),
(),
(),
(),
("MODIFIER LETTER CAPITAL C", "Lm", 0),
("MODIFIER LETTER CAPITAL F", "Lm", 0),
("MODIFIER LETTER CAPITAL Q", "Lm", 0),
("LATIN CAPITAL LETTER REVERSED HALF H", "Lu", 0),
("LATIN SMALL LETTER REVERSED HALF H", "Ll", 0),
("LATIN EPIGRAPHIC LETTER SIDEWAYS I", "Lo", 0),
("MODIFIER LETTER CAPITAL H WITH STROKE", "Lm", 0),
("MODIFIER LETTER SMALL LIGATURE OE", "Lm", 0),
("LATIN LETTER SMALL CAPITAL TURNED M", "Ll", 0),
("LATIN EPIGRAPHIC LETTER REVERSED F", "Lo", 0),
("LATIN EPIGRAPHIC LETTER REVERSED P", "Lo", 0),
("LATIN EPIGRAPHIC LETTER INVERTED M", "Lo", 0),
("LATIN EPIGRAPHIC LETTER I LONGA", "Lo", 0),
("LATIN EPIGRAPHIC LETTER ARCHAIC M", "Lo", 0),
)
|
https://github.com/EstebanMunoz/typst-template-evaluacion | https://raw.githubusercontent.com/EstebanMunoz/typst-template-evaluacion/main/template/main.typ | typst | MIT No Attribution | #import "@local/fcfm-evaluacion:0.1.0": conf, subfigures, today
// Parámetros para la configuración del documento. Descomentar aquellas que se quieran usar
#let document-params = (
"title": "Nombre evaluación",
"subject": "Tema evaluación",
"course-name": "<NAME>",
"course-code": "AB1234",
"teachers": (),
"auxiliaries": (),
"assistants": (),
"due-date": today,
"university": "Universidad de Chile",
"faculty": "Facultad de Ciencias Físicas y Matemáticas",
"department": "Departamento de Ingeniería Eléctrica",
"logo": box(height: 1.57cm, image("assets/logos/die.svg")),
)
// Aplicación de la configuración del documento
#show: doc => conf(..document-params, doc)
////////// COMIENZO DEL DOCUMENTO //////////
|
https://github.com/r8vnhill/apunte-bibliotecas-de-software | https://raw.githubusercontent.com/r8vnhill/apunte-bibliotecas-de-software/main/Unit1/Basics.typ | typst | #import "@preview/ctheorems:1.1.2": *
#show: thmrules
#let definition = thmbox("definition", "Definición", inset: (x: 1.2em, top: 1em))
== Lo básico
=== Expresiones vs. Declaraciones
En programación, es crucial distinguir entre *expresiones* y *declaraciones*, ya que cada una juega un papel diferente en la estructura y ejecución de los programas.
A continuación, se explican estos conceptos en el contexto de Kotlin, aunque es importante notar que en otros lenguajes de programación, como Scala o Rust, los ciclos pueden ser expresiones o los condicionales pueden ser declaraciones.
#definition[Expresiones][
Las expresiones son fragmentos de código que producen un valor y pueden ser compuestas con otras expresiones.
En Kotlin, las expresiones pueden ser tan simples como una constante o tan complejas como una función anónima.
Ejemplos comunes de expresiones incluyen operaciones aritméticas, operadores lógicos y llamadas a funciones.
]
#definition[Declaraciones][
Las declaraciones son fragmentos de código que realizan una acción pero no retornan un valor.
En Kotlin, las declaraciones no pueden ser compuestas con otras declaraciones, lo que significa que no pueden ser anidadas.
Ejemplos comunes de declaraciones incluyen la asignación de variables, la ejecución de ciclos y la definición de funciones.
]
=== Declaración de funciones
Una función es un bloque de código designado para realizar una tarea específica.
Está estructurada para ejecutar una secuencia de declaraciones y expresiones, y puede retornar un valor.
La sintaxis básica para declarar una función en Kotlin se muestra a continuación:
```kotlin
fun functionName(parameter1: Type1, parameter2: Type2, ...): ReturnType {
// Cuerpo de la función
return result
}
```
Donde:
- `fun` – Palabra clave utilizada para declarar funciones.
- `functionName` – Nombre de la función que la identifica y permite su invocación.
- `parameter1: Type1, parameter2: Type2, ...` – Parámetros de la función con sus tipos correspondientes.
- `ReturnType` – Tipo de dato que la función retorna al finalizar su ejecución.
A continuación, se presenta un ejemplo de una función simple en Kotlin que suma dos números enteros y retorna el
resultado:
```kotlin
fun sum(a: Int, b: Int): Int {
return a + b
}
```
Como lo que hace la función es retornar un valor, diremos que es una función de una sola expresión. En Kotlin, las
funciones de una sola expresión pueden simplificarse aún más, eliminando las llaves y la palabra clave `return`. El
ejemplo anterior se puede reescribir de la siguiente manera:
```kotlin
fun sum(a: Int, b: Int): Int = a + b
```
Esta forma más concisa de definir funciones es útil para funciones simples que consisten en una sola expresión.
Si la función es de una expresión, se puede omitir el tipo de retorno y dejar que el compilador lo infiera. Por
ejemplo, la función anterior se puede reescribir de la siguiente manera:
```kotlin
fun sum(a: Int, b: Int) = a + b
```
En este caso, el compilador infiere que la función `sum` retorna un valor de tipo `Int` al sumar los dos parámetros de tipo `Int`.
La inferencia de tipo es una característica que simplifica la sintaxis en funciones sencillas.
Sin embargo, esta característica no se aplica en funciones que contienen más de una expresión, para evitar ambigüedades y confusiones.
==== Función `main`
El punto de entrada de un programa Kotlin es la función `main`, que es el punto de inicio de la ejecución.
A continuación, se muestra un ejemplo de cómo la función `main` imprime un mensaje en la consola:
```kotlin
fun main(args: Array<String>): Unit {
println("Hello, ${args[0]}!")
}
```
En este ejemplo, la función `main` recibe un argumento de tipo `Array<String>` y
utiliza la función `println` para imprimir un mensaje en la consola.
La interpolación de cadenas en Kotlin se realiza utilizando el signo de dólar `$` seguido por la variable o expresión entre llaves `{}`, permitiendo la inserción directa de valores dentro de las cadenas de texto.
La función `println`, parte de la biblioteca estándar de Kotlin, imprime mensajes en la consola y
automáticamente añade un salto de línea al final de cada mensaje. Las funciones estándar como `println`
están disponibles globalmente sin necesidad de importaciones explícitas.
Cuando una función como `main` no retorna un valor significativo, su tipo de retorno es
`Unit`,
indicando que no hay retorno relevante. Este tipo es similar al `void` en otros lenguajes de
programación.
En Kotlin, el tipo de retorno `Unit` se puede omitir en la declaración de la función, lo que simplifica
la sintaxis, especialmente en funciones que no están destinadas a devolver ningún resultado. Por ejemplo, la
declaración de la función `main` puede omitir `Unit` y quedar de la siguiente manera:
```kotlin
fun main(args: Array<String>) {
println("Hello, ${args[0]}!")
}
```
Si quisieramos simplificar aún más la función `main`, podemos notar que la función `main` es
de una sola expresión, por lo que podemos eliminar las llaves y la palabra clave `return`</code>:
```kotlin
fun main(args: Array<String>) = println("Hello, ${args[0]}!")
```
=== Declaración de variables
En Kotlin, las variables se declaran con las palabras clave `var` y `val`.
La diferencia entre ambas es que `var` define una variable mutable, es decir, su valor puede cambiar
en cualquier momento, mientras que `val` define una variable inmutable, cuyo valor no puede ser
modificado una vez asignado.
La sintaxis básica para declarar una variable en Kotlin es la siguiente:
```kotlin
val/var variableName: Type = value
```
Donde:
- `val/var` – Palabra clave utilizada para declarar variables inmutables y mutables, respectivamente.
- `variableName` – Nombre de la variable que la identifica y permite su manipulación.
- `Type` – Tipo de dato de la variable.
- `value` – Valor inicial de la variable.
Por ejemplo:
```kotlin
val a: Int = 1 // asignación inmediata
var b = 2 // el tipo `Int` es inferido
b = 3 // Reasignar a `var` es OK
val c: Int // Tipo requerido cuando no se provee un inicializador
c = 3 // asignación diferida
a = 4 // Error: Val no puede ser reasignado
```
En el ejemplo anterior, la variable `a` es inmutable, por lo que no se puede reasignar después
de su inicialización. Por otro lado, la variable `b` es mutable, lo que permite cambiar su
valor en cualquier momento. Finalmente, la variable `c` es inmutable y se inicializa posteriormente.
Noten que si bien `val` denota una variable inmutable, no significa que el objeto al que hace referencia
sea inmutable. Por ejemplo, si la variable hace referencia a una lista mutable (representada por
`MutableList`), los elementos de la lista pueden ser modificados, aunque la variable en sí no puede ser
reasignada. Por otro lado, si la variable hace referencia a una lista inmutable (representada por
`List`), los elementos de la lista no pueden ser modificados.
==== Declaración de constantes
Además de las variables, Kotlin también facilita la declaración de constantes utilizando la palabra clave `const`.
Las constantes son variables inmutables cuyo valor se define en tiempo de compilación y
permanece constante, sin cambios durante la ejecución del programa. Por ejemplo:
```kotlin
const val NAME = "Kotlin"
const val VERSION = "1.5.21"
```
La declaración de constantes solo es permitida en el ámbito global de un archivo o dentro de un objeto de nivel
superior. No es posible declarar constantes locales dentro de funciones o bloques de código. Además, las constantes
solo pueden ser de tipos primitivos como `Int`, `Double`, `Boolean`, o `String`, y no pueden ser inicializadas con
funciones o expresiones que requieran cálculo en tiempo de ejecución.
En Kotlin, los tipos primitivos son un conjunto de tipos básicos que el sistema maneja de manera más eficiente
debido a su representación directa en la máquina subyacente. A diferencia de muchos otros lenguajes de programación,
Kotlin no tiene tipos primitivos tradicionales como en Java; en cambio, tiene clases envoltorio que corresponden a
los tipos primitivos de Java, pero con una mejor integración en el sistema de tipos de Kotlin. Estos incluyen:
- `Int`: Representa un entero de 32 bits.
- `Double`: Representa un número de punto flotante de doble precisión.
- `Boolean`: Representa un valor verdadero o falso.
- `Long`: Representa un entero de 64 bits.
- `Short`: Representa un entero de 16 bits.
- `Byte`: Representa un byte de 8 bits.
- `Float`: Representa un número de punto flotante de precisión simple.
- `Char`: Representa un carácter Unicode.
Aunque internamente Kotlin maneja estos tipos como objetos para garantizar la compatibilidad con Java y permitir una
programación más segura y versátil, en tiempo de ejecución, Kotlin optimiza el código usando representaciones
primitivas donde es posible, similar a los tipos primitivos en Java. Esta optimización asegura que las operaciones
que involucran tipos numéricos sean rápidas y eficientes.
#line(length: 100%)
*Ejercicio: Cálculo del Área de un Círculo*
1. *Definir la Constante PI*:
Declara una constante `PI` y asígnale el valor `3.14159`.
2. *Programar la Función `circleArea`*:
Implementa una función llamada `circleArea` que reciba un parámetro de tipo `Double`
representando el radio del círculo y devuelva otro `Double` que sea el área del círculo calculada
según la fórmula proporcionada.
La fórmula para calcular el área de un círculo es la siguiente:
$
A(r) = pi times r^2
$
Donde:
- $A(r)$ es el área del círculo.
- $pi$ es la constante PI.
- $r$ es el radio del círculo.
3. *Uso de la Función*:
Una vez definida la función, puedes utilizarla para calcular el área de círculos con diferentes
radios. No necesitas manejar radios negativos en esta implementación.
```kotlin
fun main() {
println("El área de un círculo de radio 5.0 es ${circleArea(5.0)}")
}
```
#line(length: 100%)
=== Expresión `if`
En Kotlin, `if` puede ser utilizado no solo como una declaración de control, sino también como una
expresión que devuelve un valor. Esto permite que `if` se incorpore directamente en el retorno de
una función. A continuación, se muestran tres formas de utilizar `if` para definir una función que
devuelve el mayor de dos números.
==== Forma Tradicional
En esta forma, `if` se utiliza en un estilo similar al de otros lenguajes de programación, donde se
maneja como una declaración condicional dentro de una función:
```kotlin
fun maxOf(a: Int, b: Int): Int {
if (a > b) {
return a
} else {
return b
}
}
```
==== Forma de Expresión con Bloques
Aquí, `if` es usado como una expresión directamente en la declaración de retorno. Esto reduce la
redundancia y simplifica la función:
```kotlin
fun maxOf(a: Int, b: Int): Int {
return if (a > b) {
a
} else {
b
}
}
```
==== Forma de Expresión Simplificada
Esta versión es la más concisa. `If` se utiliza aquí como una expresión inline dentro de la
declaración de la función. Esta forma es particularmente útil para funciones simples que se pueden
expresar en una sola línea, mejorando la claridad y concisión:
```kotlin
fun maxOf(a: Int, b: Int) = if (a > b) a else b
```
Cada una de estas formas tiene sus ventajas en diferentes contextos. La elección entre ellas depende
de la complejidad de la función y de la preferencia por la claridad o la concisión en el código.
=== Expresión `when`
La expresión `when` en Kotlin es una forma más flexible y clara de manejar múltiples condiciones
condicionales, comparada a las cadenas de `if-else`. Funciona de manera similar a `switch` en otros
lenguajes de programación pero con capacidades superiores.
==== Ejemplo sin Usar `when`
Aquí utilizamos múltiples `if-else` para evaluar y retornar un valor basado en el tipo o valor de
`obj`:
```kotlin
fun describe(obj: Any) =
if (obj == 1) "One"
else if (obj == "Hello") "Greeting"
else if (obj is Long) "Long"
else if (obj !is String) "Not a string"
else "Unknown"
```
==== Utilizando `when` con Condiciones sin Argumento
Este enfoque es similar al anterior pero usando `when` sin un argumento específico, permitiendo que
las condiciones sean expresiones booleanas arbitrarias:
```kotlin
fun describe(obj: Any): String = when {
obj == 1 -> "One"
obj == "Hello" -> "Greeting"
obj is Long -> "Long"
obj !is String -> "Not a string"
else -> "Unknown"
}
```
==== Utilizando `when` con Argumento
Aquí, `when` se utiliza de manera más idiomática, con el objeto de la evaluación (`obj`) como
argumento de `when`, simplificando aún más las condiciones:
```kotlin
fun describe(obj: Any): String = when (obj) {
1 -> "One"
"Hello" -> "Greeting"
is Long -> "Long"
!is String -> "Not a string"
else -> "Unknown"
}
```
==== Ventajas de Usar `when`
- *Claridad*: `when` reduce la complejidad visual y mejora la legibilidad, especialmente con
múltiples condiciones.
- *Flexibilidad*: `when` permite la evaluación de tipos, valores y condiciones complejas en una
única estructura controlada.
- *Mantenibilidad*: Código escrito con `when` es generalmente más fácil de modificar que las largas
cadenas de `if-else`.
#line(length: 100%)
*Ejercicio: Reescribir usando una expresión `when`*
Reescribe el siguiente código como una función de una expresión que utilice una expresión `when`:
```kotlin
fun login(username: String, passowrd: String): Boolean {
if (loginAttempts >= MAX_LOGIN_ATTEMPTS) {
return false
}
if (isValidPassword(password)) {
loginAttempts = 0
return true
}
loginAttempts++
return false
}
```
#line(length: 100%)
=== Declaración `for`
La declaración `for` en Kotlin es una herramienta poderosa para iterar sobre colecciones y rangos. A
continuación, se presenta cómo se puede utilizar para recorrer diferentes estructuras de datos y
realizar operaciones sobre sus elementos.
==== Ejemplo Básico: Iteración sobre una Lista
El siguiente ejemplo muestra cómo usar el ciclo `for` para iterar sobre una lista de strings e
imprimir cada elemento:
```kotlin
fun forExample() {
val items = listOf("apple", "banana", "kiwi")
for (item in items) {
println(item)
}
}
```
*Explicación*:
- `items` es una lista de strings.
- `for (item in items)` inicia un bucle que recorre cada elemento de la lista `items`.
- `println(item)` imprime cada elemento de la lista.
==== Uso Avanzado: Iteración sobre un Rango de Números
Kotlin permite iterar no solo sobre colecciones, sino también sobre rangos de números. Esto es
especialmente útil para realizar operaciones repetitivas un número específico de veces o para generar
secuencias numéricas.
```kotlin
fun rangeExample() {
for (i in 1..5) {
println(i)
}
}
```
*Explicación*:
- `for (i in 1..5)` inicia un bucle que recorre los números del 1 al 5, inclusive.
- `println(i)` imprime cada número del 1 al 5.
==== Iteración con Índices
En ocasiones, puede ser útil tener acceso al índice de cada elemento durante la iteración. Kotlin
facilita esto con la función `withIndex()`.
```kotlin
fun indexExample() {
val items = listOf("apple", "banana", "kiwi")
for ((index, value) in items.withIndex()) {
println("Item at $index is $value")
}
}
```
*Explicación*:
- `items.withIndex()` devuelve una colección de pares, cada uno compuesto por un índice y el valor correspondiente.
- `for ((index, value) in items.withIndex())` itera sobre estos pares.
- `println("Item at $index is $value")` imprime el índice y el valor de cada elemento en la lista.
=== Declaración `while`
La declaración `while` es fundamental para realizar bucles basados en una condición que necesita ser
evaluada antes de cada iteración del ciclo. Es especialmente útil cuando el número de iteraciones no
se conoce de antemano.
==== Ejemplo Básico: Conteo Regresivo
Aquí, `while` se utiliza para realizar un conteo regresivo desde 5 hasta 1:
```kotlin
fun whileExample() {
var x = 5
while (x > 0) {
println(x)
x-- // Decrementa x en 1 en cada iteración
}
}
```
*Explicación*:
- `var x = 5` inicializa una variable `x` con el valor 5.
- `while (x > 0)` continúa el bucle mientras `x` sea mayor que 0.
- `println(x)` imprime el valor actual de `x`.
- `x--` reduce el valor de `x` en 1 después de cada iteración, asegurando que el bucle eventualmente
terminará cuando `x` sea 0.
==== Ejemplo Avanzado: Búsqueda en Lista
`while` también puede ser útil para buscar un elemento en una lista hasta que se encuentre un elemento específico o se agote la lista:
```kotlin
fun searchExample() {
val items = listOf("apple", "banana", "kiwi")
var index = 0
while (index < items.size && items[index] != "banana") {
index++
}
if (index < items.size) {
println("Found banana at index $index")
} else {
println("Banana not found")
}
}
```
*Explicación*:
- `while (index < items.size && items[index] != "banana")` sigue iterando mientras el índice sea
menor que el tamaño de la lista y el elemento actual no sea "banana".
- `index++` incrementa el índice en cada iteración para revisar el siguiente elemento en la lista.
- La condición de salida del ciclo asegura que no se exceda el límite de la lista y se detenga la búsqueda una vez que se encuentre "banana".
==== Comparación con `do-while`
Es útil comparar `while` con `do-while` para resaltar que `while` evalúa su condición antes de la
primera iteración del bucle, mientras que `do-while` garantiza que el cuerpo del ciclo se ejecutará
al menos una vez porque la condición se evalúa después de la ejecución del cuerpo.
```kotlin
fun doWhileExample() {
var y = 5
do {
println(y)
y--
} while (y > 0)
}
```
Este ejemplo garantiza que el contenido dentro de `do` se ejecuta al menos una vez,
independientemente de la condición inicial, lo cual es una distinción crucial en ciertos escenarios
de programación.
Estas expansiones y discusiones proporcionarán a los estudiantes una comprensión más completa de
cuándo y cómo usar `while` de manera efectiva en Kotlin.
=== Rangos
En Kotlin, los rangos permiten iterar de manera eficiente y elegante sobre secuencias numéricas.
Recientemente, se ha introducido el estándar `..<` para crear rangos exclusivos, reemplazando el uso
más antiguo de `until` en nuevos desarrollos.
==== Ejemplos de Rangos
1. *Rango Inclusivo (`..`)*:
Este tipo de rango incluye ambos extremos, ideal para situaciones donde se necesita incluir el
valor final en las operaciones.
```kotlin
for (i in 1..5) print(i) // Imprime: 12345
```
`1..5` crea un rango que incluye del 1 al 5.
2. *Rango Exclusivo (`..<`)*:
`..<` se usa para generar rangos que excluyen el valor final, proporcionando una forma directa y
legible de definir límites en iteraciones.
```kotlin
for (i in 1..<5) print(i) // Imprime: 1234
```
`1..<5` produce un rango desde 1 hasta 4, excluyendo el 5. Esta sintaxis es más intuitiva para
quienes están familiarizados con lenguajes como Swift.
3. *Rango Decreciente con Paso (`downTo` con `step`)*:
Kotlin también permite definir rangos decrecientes con un intervalo específico entre valores, lo que es útil para decrementos no estándar.
```kotlin
for (i in 5 downTo 1 step 2) print(i) // Imprime: 531
```
`5 downTo 1 step 2` crea un rango que empieza en 5 y termina en 1, incluyendo solo cada segundo número (decrementando de dos en dos).
#line(length: 100%)
*Ejercicio: Suma de un Rango de Números*
Desarrolla una función en llamada `sumRange(a: Int, b: Int): Int` que calcule y retorne la suma de
todos los números entre dos enteros `a` y `b`, incluyendo ambos extremos.
Instrucciones
1. *Implementación de la Función*: La función debe usar una declaración `for` para iterar a través
de un rango de números desde `a` hasta `b`.
2. *Manejo de Rangos*:
- Si `a` es menor o igual que `b`, el rango debe ir de `a` a `b`.
- Si `a` es mayor que `b`, el rango debe ir de `a` a `b` en orden inverso (es decir, decreciendo).
#line(length: 100%)
|
|
https://github.com/SE-legacy/templatesTypst | https://raw.githubusercontent.com/SE-legacy/templatesTypst/master/main.typ | typst | #import "conf.typ" : conf
// #import "@preview/cetz:0.2.2"
#import "@preview/plotst:0.2.0": *
#import "@preview/fletcher:0.4.5" as fletcher: diagram, node, edge
#show: conf.with(
title: [Test Syntax],
type: "referat",
info: (
author: (
name: [<NAME>],
faculty: [КНиИТ],
group: "251",
sex: "male"
),
inspector: (
degree: "",
name: ""
)
),
settings: (
title_page: (
enabled: true
),
contents_page: (
enabled: true
)
)
)
= Test math example
1. Limits & sqrt(root)
$limits(l i m)_(n -> infinity) root(n, a) = 1$
2. Sum
$(1 + x)^n = limits(sum)_(k = 0)^n C_n^k x^k $
3. Integral
$integral, integral.double, integral.cont, integral.dash, integral.triple, $ ...
$limits(integral.double)_D f(x,y) d x d y = limits(integral)_a^b d x limits(integral)_(phi_1(x))^(phi_2(x)) f(x,y) d y$
$limits(integral)_(-pi/2)^((3pi)/2) d x limits(integral)_(-1)^(sin (x)) f(x,y) d y + limits(integral)_(pi/2)^((5pi)/2) d x limits(integral)_(sin x)^(1) f(x,y) d y$
4. Matrix, determinant, vector
$mat(
1, 2, 3;
4, 5, 6;
7, 8, 9
) $
$mat(
1, 2, 3;
4, 5, 6;
7, 8, 9;
delim: "|"
) $
$mat(
1, 2, 3;
4, 5, 6;
7, 8, 9;
delim: "["
) $
$vec(
1, 2, 3,
delim: "["
)$
$vec(
1, 2, 3,
)$
5. Frac
$frac(a^2, 2) = (a^2)/2$
= Test table
#set table.hline(stroke: .6pt)
#table(
columns: (auto, auto, auto),
stroke: none,
inset: 10pt,
align: horizon,
table.hline(),
table.header(
[*Something*], [*Area*], [*Parameters*],
),
table.hline(),
table.vline(x: 0),
table.vline(x: 1),
table.vline(x: 2),
table.vline(x: 3),
// image("cylinder.svg"),
[9],
$ pi h (D^2 - d^2) / 4 $,
[
$h$: height \
$D$: outer radius \
$d$: inner radius
],
table.hline(),
// image("tetrahedron.svg"),
[9],
$ sqrt(2) / 12 a^3 $,
[$a$: edge length],
table.hline(start: 1),
[9],
$ sqrt(2) / 12 a^3 $,
[$a$: edge length],
table.hline(),
)
= Assembler table template
// NOTE: Assembler table template
#set text(
size: 11pt
)
#set table.hline(stroke: .6pt)
#table(
// set text(1pt),
columns: 13,
stroke: none,
inset: 2.5pt,
align: center,
table.hline(),
table.header(
[*Шаг*],
[*Машинный
\код*],
[*Команда*],
table.cell(colspan: 9,
[*Регистры*]
),
[*Флаги*],
table.hline(start: 3),
[ ], [ ], [ ], [AX], [BX], [CX], [DX], [SP], [DS], [SS], [CS], [IP], [CZSOPAID],
),
table.hline(),
table.vline(x: 0),
table.vline(x: 1),
table.vline(x: 2),
table.vline(x: 3),
table.vline(x: 4, start: 1),
table.vline(x: 5, start: 1),
table.vline(x: 6, start: 1),
table.vline(x: 7, start: 1),
table.vline(x: 8, start: 1),
table.vline(x: 9, start: 1),
table.vline(x: 10, start: 1),
table.vline(x: 11, start: 1),
table.vline(x: 12 ),
table.vline(x: 13),
[0], [], [],
// регистры AX, BX, CX, DX
[0000], [0000], [0000], [0000],
// регистр SP
[0100],
// регистры DS, SS, CS
[489D], [48B2], [48AD],
// регистр IP
[0000],
// флаги
[00000010],
table.hline(),
[1], [B8B048], [mov ax,48B0],
// регистры AX, BX, CX, DX
[48B0], [0000], [0000], [0000],
// регистр SP
[0100],
// регистры DS, SS, CS
[489D], [48B2], [48AD],
// регистр IP
[0003],
// флаги
[00000010],
table.hline(),
[2], [8ED8], [mov ds,ax],
// регистры AX, BX, CX, DX
[48B0], [0000], [0000], [0000],
// регистр SP
[0100],
// регистры DS, SS, CS
[48B0], [48B2], [48AD],
// регистр IP
[0005],
// флаги
[00000010],
table.hline(),
)
= Test Graphs
#let print(desc: "", content) = {
desc
repr(content)
[ \ ]
}
#let scatter_plot_test() = {
let gender_data = (
("w", 1), ("w", 3), ("w", 5), ("w", 4), ("m", 2), ("m", 2), ("m", 4), ("m", 6), ("d", 1), ("d", 9), ("d", 5), ("d", 8), ("d", 3), ("d", 1)
)
let y_axis = axis(min: 0, max: 11, step: 1, location: "left", helper_lines: true, invert_markings: false, title: "foo", value_formatter: "{}€")
let y_axis_right = axis(min: 1, max: 11, step: 1, location: "right", helper_lines: false, invert_markings: false, title: "foo", stroke: 7pt + red, show_arrows: false, value_formatter: i => datetime(year: 1984, month: 1, day: i).display("[day].[month]."))
let gender_axis_x = axis(values: ("", "m", "w", "d"), location: "bottom", helper_lines: true, invert_markings: false, title: "Gender", show_arrows: false)
let pl = plot(data: gender_data, axes: (gender_axis_x, y_axis, y_axis_right))
scatter_plot(pl, (100%,50%))
let data = (
(0, 0), (2, 2), (3, 0), (4, 4), (5, 7), (6, 6), (7, 9), (8, 5), (9, 9), (10, 1)
)
let x_axis = axis(min: 0, max: 11, step: 2, location: "bottom")
let y_axis = axis(min: 0, max: 11, step: 2, location: "left", helper_lines: false, show_values: false)
let pl = plot(data: data, axes: (x_axis, y_axis))
scatter_plot(pl, (100%, 25%))
}
// HACK: самый востребованный вариант
#let graph_plot_test() = {
let data = (
(0, 4), (2, 2), (3, 0), (4, 4), (5, 7), (6, 6), (7, 9), (8, 5), (9, 9), (10, 1)
)
let data2 = (
(0, 0), (2, 2), (3, 1), (4, 4), (5, 2), (6, 6), (7, 5), (8, 7), (9, 10), (10, 3)
)
let x_axis = axis(min: 0, max: 11, step: 2, location: "bottom")
let y_axis = axis(min: 0, max: 11, step: 2, location: "left", helper_lines: false)
let pl = plot(data: data, axes: (x_axis, y_axis))
graph_plot(pl, (100%, 25%), markings: [])
graph_plot(pl, (100%, 25%), markings: [ #circle(radius: 2pt, fill: black) ])
graph_plot(pl, (100%, 25%), rounding: 30%, caption: "Graph Plot with caption and rounding", markings: [#circle(radius: 3pt, fill: black)])
}
#let histogram_test() = {
let data = (
18000, 18000, 18000, 18000, 18000, 18000, 18000, 18000, 18000, 18000, 28000, 28000, 28000, 28000, 28000, 28000, 28000, 28000, 28000, 28000,28000, 28000, 28000, 28000, 28000, 28000, 28000, 28000, 28000, 28000, 28000, 28000, 35000, 46000, 75000, 95000
)
let classes = class_generator(10000, 50000, 4)
classes.push(class(50000, 100000))
classes = classify(data, classes)
let x_axis = axis(min: 0, max: 100000, step: 10000, location: "bottom")
let y_axis = axis(min: 0, max: 31, step: 5, location: "left", helper_lines: true)
let pl = plot(data: classes, axes: (x_axis, y_axis))
histogram(pl, (100%, 40%), stroke: black, fill: (purple, blue, red, green, yellow))
}
#let histogram_test_2() = {
let classes = ()
classes.push(class(11, 13))
classes.push(class(13, 15))
classes.push(class(1, 6))
classes.push(class(6, 11))
classes.push(class(15, 30))
let data = ((20, 2), (30, 7), (16, 12), (40, 13), (5, 17))
let x_axis = axis(min: 0, max: 31, step: 1, location: "bottom", show_markings: false)
let y_axis = axis(min: 0, max: 41, step: 5, location: "left", helper_lines: true)
classes = classify(data, classes)
let pl = plot(axes: (x_axis, y_axis), data: classes)
histogram(pl, (100%, 40%))
}
#let pie_chart_test() = {
show: r => columns(2, r)
let data = ((10, "Male"), (20, "Female"), (15, "Divers"), (2, "Other"))
let data2 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
let p = plot(data: data)
pie_chart(p, (100%, 20%), display_style: "legend-inside-chart")
pie_chart(p, (100%, 20%), display_style: "hor-chart-legend")
pie_chart(p, (100%, 20%), display_style: "hor-legend-chart")
pie_chart(p, (100%, 20%), display_style: "vert-chart-legend")
pie_chart(p, (100%, 20%), display_style: "vert-legend-chart")
}
#let bar_chart_test() = {
let data = ((10, "Monday"), (5, "Tuesday"), (15, "Wednesday"), (9, "Thursday"), (11, "Friday"))
let y_axis = axis(values: ("", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"), location: "left", show_markings: true)
let x_axis = axis(min: 0, max: 20, step: 2, location: "bottom", helper_lines: true)
let pl = plot(axes: (x_axis, y_axis), data: data)
bar_chart(pl, (100%, 33%), fill: (purple, blue, red, green, yellow), bar_width: 70%, rotated: true)
let data_2 = ((20, 2), (30, 7), (16, 12), (40, 13), (5, 17))
let y_axis_2 = axis(min: 0, max: 41, step: 5, location: "left", show_markings: true, helper_lines: true)
let x_axis_2 = axis(min: 0, max: 21, step: 1, location: "bottom")
let pl_2 = plot(axes: (x_axis_2, y_axis_2), data: data_2)
bar_chart(pl_2, (100%, 60%), bar_width: 100%)
}
// TODO
#let overlay_test() = {
let data_scatter = (
(0, 0), (2, 2), (3, 0), (4, 4), (5, 7), (6, 6), (7, 9), (8, 5), (9, 9), (10, 1)
)
let data_graph = (
(0, 3), (1, 5), (2, 1), (3, 7), (4, 3), (5, 5), (6, 7),(7, 4),(11, 6)
)
let x_axis = axis(min: 0, max: 11, step: 2, location: "bottom")
let y_axis = axis(min: 0, max: 11, step: 2, location: "left", helper_lines: false)
let pl_scatter = plot(data: data_scatter, axes: (x_axis, y_axis))
let scatter_display = scatter_plot(pl_scatter, (100%, 25%), stroke: red)
let pl_graph = plot(data: data_graph, axes: (x_axis, y_axis))
let graph_display = graph_plot(pl_graph, (100%, 25%), stroke: blue)
scatter_display
graph_display
overlay((scatter_display, graph_display), (100%, 25%))
x_axis = axis(min: 0, max: 11, step: 2, location: "bottom", show_values: false)
y_axis = axis(min: 0, max: 11, step: 2, location: "left", show_values: false)
let ice = (data: ((0,0),(3,3),(0,10)), axes: (x_axis, y_axis))
let a = graph_plot(ice, (100%, 25%), fill: blue.lighten(50%), markings: none, stroke: none, caption: "foo")
let water = (data: ((0,0),(3,3),(10,7), (10,0)), axes: (x_axis, y_axis))
let b = graph_plot(water, (100%, 25%), fill: blue, markings: none, stroke: none)
let steam = (data: ((3,3),(10,7),(10,10),(0,10)), axes: (x_axis, y_axis))
let c = graph_plot(steam, (100%, 25%), fill: yellow, markings: none, stroke: none)
overlay((a, b, c), (50%, 25%))
}
#let radar_test() = {
let data = (
(0,6),(1,7),(2,5),(3,4),(4,4),(5,7),(6,6),(7,6),
)
let y_axis = axis(min:0, max: 8, location: "left", helper_lines: true)
let x_axis = axis(min:0, max: 8, location: "bottom")
let pl = plot(data: data, axes: (x_axis, y_axis))
radar_chart(pl, (60%,60%))
}
// BUG: хз почему но оно не работает, тк я все эти графики взял тупо с официального примера на github
// проблема не во мне
// #let function_test() = {
// let data = function_plotter(x => {2*(x*x) + 3*x + 3}, 0, 8.3, precision: 100)
// let data2 = function_plotter(x => {1*(x*x) + 3*x + 3}, 0, 11.4, precision: 100)
// let x_axis = axis(min: 0, max: 20, step: 1, location: "bottom")
// let y_axis = axis(min: 0, max: 151, step: 50, location: "left", helper_lines: true)
// let p1 = graph_plot(plot(axes: (x_axis, y_axis), data: data), (100%, 50%), markings: [], stroke: red)
// let p2 = graph_plot(plot(axes: (x_axis, y_axis), data: data2), (100%, 50%), markings: [], stroke: green)
// overlay((p1, p2), (100%, 50%))
// }
// BUG: аналогично предыдущему багу
// #let box_plot_test() = {
// box_plot(box_width: 70%, pre_calculated: false, plot(axes: (
// axis(values: ("", "(a)", "(b)", "(c)"), location: "bottom", show_markings: false),
// axis(min: 0, max: 10, step: 1, location: "left", helper_lines: true),
// ),
// data:((1, 3, 4, 4, 5, 6, 7, 8), (1, 3, 4, 4, 5, 7, 8), (1, 3, 4, 5, 7))
// ), (100%, 40%), caption: none)
// }
// BUG: аналогично предыдущему багу
// #let cumsum_test() = {
// datetime(year: 2023, month: 1, day: 20) - datetime.today()
// let data = range(1,31).map(i=> (datetime(year: 2023, month: 1, day: i),2))
// let dates = data.map(it => it.at(0))
// let newdata = ()
// let sum = 0
// for d in data {
// sum += d.at(1)
// newdata.push((d.at(0).display(), sum))
// }
// let _ = newdata.remove(0)
// let x_axis = axis(values: dates.map(it=> it.display()), location: "bottom")
// let y_axis = axis(min: 0, max: sum, step: 10, location: "left")
// graph_plot(plot(axes: (x_axis, y_axis), data: newdata), (100%, 50%), markings: [])
// }
#let paper_test() = {
set par(justify: true)
pagebreak()
[
#set align(center)
= This is my paper
#set align(left)
#show: r => columns(2, r)
#lorem(100)
== Scatter plots
#lorem(50)
#{
let data = (
(0, 0), (1, 2), (2, 4), (3, 6), (4, 8), (5, 3), (6, 6),(7, 9),(11, 12)
)
let x_axis = axis(min: 0, max: 11, step: 1, location: "bottom")
let y_axis = axis(min: 0, max: 13, step: 2, location: "left", helper_lines: true)
let p = plot(data: data, axes: (x_axis, y_axis))
scatter_plot(p, (100%, 20%))
}
== Histograms
#lorem(150)
#{
let data = (
18000, 18000, 18000, 18000, 18000, 18000, 18000, 18000, 18000, 18000, 28000, 28000, 28000, 28000, 28000, 28000, 28000, 28000, 28000, 28000,28000, 28000, 28000, 28000, 28000, 28000, 28000, 28000, 28000, 28000, 28000, 28000, 35000, 46000, 75000, 95000
)
let classes = class_generator(10000, 50000, 4)
classes.push(class(50000, 100000))
classes = classify(data, classes)
let x_axis = axis(min: 0, max: 100000, step: 20000, location: "bottom", show_markings: false, title: "Wert x", )
let y_axis = axis(min: 0, max: 26, step: 3, location: "left", helper_lines: true, title: "Wert y und anderes Zeug", )
let pl = plot(data: classes, axes: (x_axis, y_axis))
histogram(pl, (100%, 20%), stroke: black, fill: gray)
}
== Pie charts
#{
lorem(120)
let data = ((10, "Male"), (20, "Female"), (15, "Divers"), (2, "Other"))
let pl = plot(data: data)
pie_chart(pl, (100%, 20%), display_style: "hor-chart-legend")
}
#{
let data = ((5, "0-18"), (9, "18-30"), (25, "30-60"), (7, "60+"))
let pl = plot(data: data)
pie_chart(pl, (100%, 20%), display_style: "hor-chart-legend")
lorem(200)
}
== Bar charts
#{
lorem(50)
let data = ((10, "Monday"), (5, "Tuesday"), (15, "Wednesday"), (9, "Thursday"), (11, "Friday"))
let y_axis = axis(values: ("", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"), location: "left", show_markings: true)
let x_axis = axis(min: 0, max: 20, step: 2, location: "bottom", helper_lines: true, title: "Visitors")
let pl = plot(axes: (x_axis, y_axis), data: data)
bar_chart(pl, (100%, 140pt), fill: (purple, blue, red, green, yellow), bar_width: 70%, rotated: true)
let data_2 = ((20, 2), (30, 3), (16, 4), (40, 6), (5, 7))
let y_axis_2 = axis(min: 0, max: 41, step: 10, location: "left", show_markings: true, helper_lines: true)
let x_axis_2 = axis(min: 0, max: 9, step: 1, location: "bottom")
let pl_2 = plot(axes: (x_axis_2, y_axis_2), data: data_2)
bar_chart(pl_2, (100%, 120pt), fill: (purple, blue, red, green, yellow), bar_width: 70%)
lorem(95)
}
]
}
// NOTE: вызов функций описанных выше
#{
scatter_plot_test()
graph_plot_test()
pagebreak()
histogram_test()
histogram_test_2()
pagebreak()
pie_chart_test()
pagebreak()
bar_chart_test()
overlay_test()
radar_test()
// pagebreak()
// BUG: не работают
// function_test()
// box_plot_test()
// cumsum_test()
paper_test()
}
= Test Diograms
// a quick and dirty horizontal arrow created as a polygon
#let block-arrow(length, width, head-length, head-width, fill) = {
box(width: length, height: head-width, {
polygon(
(0%, 50% + width/2),
(100% - head-length, 50% + width/2),
(100% - head-length, 50% + head-width/2),
(100%, 50%),
(100% - head-length, 50% - head-width/2),
(100% - head-length, 50% - width/2),
(0%, 50% - width/2),
stroke: none,
fill: fill,
)
})
}
#diagram(
edge-stroke: 1pt,
node-stroke: 1pt,
node-corner-radius: 5pt,
edge-corner-radius: 8pt,
mark-scale: 80%,
{
let start = (0, 0)
let foo = (1, 0)
let bar = (2, 0)
let baz = (1, 1)
let quux = (2, 1)
let end = (3, 0)
// an empty, small circular node
let terminal(..args) = node(
// position, and any other parameters
..args,
// draw the node outline ...
shape: circle,
// ... with small padding ...
inset: 3pt,
// ... around very small invisible content
h(1pt)
)
//
let regular(..args) = node(
// position, and any other parameters
..args,
width: 4em,
height: 3em,
fill: aqua,
)
let arrow(..args) = edge(..args, "-|>")
terminal(start)
regular(foo)[foo]
regular(bar)[bar]
regular(baz)[baz]
regular(quux)[quux]
terminal(end)
arrow(start, foo)
arrow(foo, bar)
arrow(bar, end)
arrow(start, (0.3, 0), (0.3, 1), baz)
arrow(baz, quux)
arrow(quux, (2.6, 1), (2.6, 0), end)
node(
enclose: ((1, -0.6), (2, -0.6)),
stroke: none,
// here we have a fixed "regular" node width
// of 4em, so we need to extend the node
// content's width by 2em on both sides
pad(x: -2em, y: 2em, {
[Tweedledee]
block-arrow(100%, 5pt, 16pt, 14pt, red)
})
)
node(
enclose: ((1, 1.6), (2, 1.6)),
stroke: none,
pad(x: -2em, {
block-arrow(100%, 5pt, 16pt, 14pt, green)
[Tweedledum]
})
)
}
)
|
|
https://github.com/florianhartung/studienarbeit | https://raw.githubusercontent.com/florianhartung/studienarbeit/main/work/dhbw_template/declaration_of_authenticity.typ | typst | #let labeled_field(label, width) = [
#v(2.2em)
#line(length: width)
#v(-0.3em)
#h(5mm)
#label
];
#let declaration_of_authenticity(title) = [
#box(
width: 100%,
stroke: black,
inset: 4mm,
)[
#set par(justify: true)
#align(center)[*Erklärung zur Eigenleistung*]
Ich versichere hiermit, dass ich meine Projektarbeit mit dem \
#v(3mm)
THEMA \
*#title*
#v(2mm)
selbstständig verfasst und keine anderen als die angegebenen Quellen und
Hilfsmittel benutzt habe. Ich versichere zudem, dass die eingereichte
elektronische Fassung mit der gedruckten Fassung übereinstimmt.
#grid(
columns: (40%, 60%),
labeled_field([Ort, Datum], 90%),
labeled_field([Unterschrift], 90%),
)
]
] |
|
https://github.com/kdog3682/mathematical | https://raw.githubusercontent.com/kdog3682/mathematical/main/0.1.0/src/lightning.typ | typst | #import "@local/typkit:0.1.0": *
//
#let lightning-question(s, number: 1) = {
}
// Shows a lightning bolt table for fast math questions
#let lightning-round(..sink) = {
let questions = sink.pos()
vertical-table(..globals.table-reset, ..questions)
// it should be a table that goes downwards
}
#let question = lightning-question
#let round = lightning-round
|
|
https://github.com/ahplev/notes | https://raw.githubusercontent.com/ahplev/notes/main/misc/pade_appr/pade_appr.typ | typst | #set text(
font: "Noto Sans SignWriting Regular",
)
#set math.equation(numbering: "(1)")
== Pade approximant
Pade approximant of order [$m slash n]$ is the rational function also denoted as $[m slash n]_f (x)$
$ R(x) = (sum_(j=0)^m a_j x^j)/(1+sum_(k=1)^n b_k x^k) = (a_0 + a_1 x+ a_2 x^2 + dots.h + a_m x^m)/(1 + b_1 x + b_2 x^2 + dots.h + b_n x^n) $
which agrees with $f(x)$ to the highest possible order, i.e.
$ f(0) &= R(0) \ f'(0) &= R'(0) \ f''(0) &= R''(0) \ &dots.v \ f^((m+n)) (0) &= R^((m+n))(0) $
To calculate the coefficients, we write the formula
$ [m slash n]_f (x) = f(0) + f'(0) x + (f''(0))/(k!) x^2 + dots.h + (f^((m + n))(0))/((m+n)!) x^(m+n) $
this says the pade approximant is an approximation of function $f$ to the order of $m+n $, i.e.
$ f(x) = [m slash n]_f (x) + O(x^(m+n+1)) $
plugging in the definition and solving the undetermined coefficients
$ sum_(j=0)^m a_j x^j = (1 + sum_(k = 1)^n b_k x^k)sum_(i = 0)^(m+n) (f^((k))(0))/(k!)x^k $
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-10480.typ | typst | Apache License 2.0 | #let data = (
("OSMANYA LETTER ALEF", "Lo", 0),
("OSMANYA LETTER BA", "Lo", 0),
("OSMANYA LETTER TA", "Lo", 0),
("OSMANYA LETTER JA", "Lo", 0),
("OSMANYA LETTER XA", "Lo", 0),
("OSMANYA LETTER KHA", "Lo", 0),
("OSMANYA LETTER DEEL", "Lo", 0),
("OSMANYA LETTER RA", "Lo", 0),
("OSMANYA LETTER SA", "Lo", 0),
("OSMANYA LETTER SHIIN", "Lo", 0),
("OSMANYA LETTER DHA", "Lo", 0),
("OSMANYA LETTER CAYN", "Lo", 0),
("OSMANYA LETTER GA", "Lo", 0),
("OSMANYA LETTER FA", "Lo", 0),
("OSMANYA LETTER QAAF", "Lo", 0),
("OSMANYA LETTER KAAF", "Lo", 0),
("OSMANYA LETTER LAAN", "Lo", 0),
("OSMANYA LETTER MIIN", "Lo", 0),
("OSMANYA LETTER NUUN", "Lo", 0),
("OSMANYA LETTER WAW", "Lo", 0),
("OSMANYA LETTER HA", "Lo", 0),
("OSMANYA LETTER YA", "Lo", 0),
("OSMANYA LETTER A", "Lo", 0),
("OSMANYA LETTER E", "Lo", 0),
("OSMANYA LETTER I", "Lo", 0),
("OSMANYA LETTER O", "Lo", 0),
("OSMANYA LETTER U", "Lo", 0),
("OSMANYA LETTER AA", "Lo", 0),
("OSMANYA LETTER EE", "Lo", 0),
("OSMANYA LETTER OO", "Lo", 0),
(),
(),
("OSMANYA DIGIT ZERO", "Nd", 0),
("OSMANYA DIGIT ONE", "Nd", 0),
("OSMANYA DIGIT TWO", "Nd", 0),
("OSMANYA DIGIT THREE", "Nd", 0),
("OSMANYA DIGIT FOUR", "Nd", 0),
("OSMANYA DIGIT FIVE", "Nd", 0),
("OSMANYA DIGIT SIX", "Nd", 0),
("OSMANYA DIGIT SEVEN", "Nd", 0),
("OSMANYA DIGIT EIGHT", "Nd", 0),
("OSMANYA DIGIT NINE", "Nd", 0),
)
|
https://github.com/Relacibo/typst-as-lib | https://raw.githubusercontent.com/Relacibo/typst-as-lib/main/examples/templates/resolve_static.typ | typst | MIT License | #import "function.typ": alert
#figure(
image("./images/typst.png", width: 80pt),
caption: [
Typst logo
],
)
#alert[Static]
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-1F000.typ | typst | Apache License 2.0 | #let data = (
("MAHJONG TILE EAST WIND", "So", 0),
("MAHJONG TILE SOUTH WIND", "So", 0),
("MAHJONG TILE WEST WIND", "So", 0),
("MAHJONG TILE NORTH WIND", "So", 0),
("MAHJONG TILE RED DRAGON", "So", 0),
("MAHJONG TILE GREEN DRAGON", "So", 0),
("MAHJONG TILE WHITE DRAGON", "So", 0),
("MAHJONG TILE ONE OF CHARACTERS", "So", 0),
("MAHJONG TILE TWO OF CHARACTERS", "So", 0),
("MAHJONG TILE THREE OF CHARACTERS", "So", 0),
("MAHJONG TILE FOUR OF CHARACTERS", "So", 0),
("MAHJONG TILE FIVE OF CHARACTERS", "So", 0),
("MAHJONG TILE SIX OF CHARACTERS", "So", 0),
("MAHJONG TILE SEVEN OF CHARACTERS", "So", 0),
("MAHJONG TILE EIGHT OF CHARACTERS", "So", 0),
("MAHJONG TILE NINE OF CHARACTERS", "So", 0),
("MAHJONG TILE ONE OF BAMBOOS", "So", 0),
("MAHJONG TILE TWO OF BAMBOOS", "So", 0),
("MAHJONG TILE THREE OF BAMBOOS", "So", 0),
("MAHJONG TILE FOUR OF BAMBOOS", "So", 0),
("MAHJONG TILE FIVE OF BAMBOOS", "So", 0),
("MAHJONG TILE SIX OF BAMBOOS", "So", 0),
("MAHJONG TILE SEVEN OF BAMBOOS", "So", 0),
("MAHJONG TILE EIGHT OF BAMBOOS", "So", 0),
("MAHJONG TILE NINE OF BAMBOOS", "So", 0),
("MAHJONG TILE ONE OF CIRCLES", "So", 0),
("MAHJONG TILE TWO OF CIRCLES", "So", 0),
("MAHJONG TILE THREE OF CIRCLES", "So", 0),
("MAHJONG TILE FOUR OF CIRCLES", "So", 0),
("MAHJONG TILE FIVE OF CIRCLES", "So", 0),
("MAHJONG TILE SIX OF CIRCLES", "So", 0),
("MAHJONG TILE SEVEN OF CIRCLES", "So", 0),
("MAHJONG TILE EIGHT OF CIRCLES", "So", 0),
("MAHJONG TILE NINE OF CIRCLES", "So", 0),
("MAHJONG TILE PLUM", "So", 0),
("MAHJONG TILE ORCHID", "So", 0),
("MAHJONG TILE BAMBOO", "So", 0),
("MAHJONG TILE CHRYSANTHEMUM", "So", 0),
("MAHJONG TILE SPRING", "So", 0),
("MAHJONG TILE SUMMER", "So", 0),
("MAHJONG TILE AUTUMN", "So", 0),
("MAHJONG TILE WINTER", "So", 0),
("MAHJONG TILE JOKER", "So", 0),
("MAHJONG TILE BACK", "So", 0),
)
|
https://github.com/i-am-wololo/cours | https://raw.githubusercontent.com/i-am-wololo/cours/master/main/cheatsheet.typ | typst | #import "./templates.typ": *
#show: chshtemplate.with(matiere: "i23")
#include "./parties_i23/logique.typ"
#include "./parties_i23/axioms_predicats.typ"
#include "./parties_i23/CalculBool.typ"
#include "./parties_i23/relations.typ"
#include "./parties_i23/AnalCombinatoire.typ"
#include "./parties_i23/arithmetique.typ"
// = Connecteurs logique:
// #table(
|
|
https://github.com/exdevutem/taller-git | https://raw.githubusercontent.com/exdevutem/taller-git/main/src/issues.typ | typst | = Issues <issues>
En github, un Issue se refiere a un problema que se haya encontrado con el proyecto, del cual no se ha creado cambios aún. Estos varían enormemente; podrías levantar un Issue para informar de un bug que hayas encontrado en el programa, para solicitar que se implemente una nueva característica, para discutir el curso de acción del proyecto, para solicitar el cambio o eliminación de alguna característica, #link("https://github.com/twitter/the-algorithm/issues?page=26&q=is%3Aissue+is%3Aclosed")[para webiar a Elon Musk], etc, etc.
#figure(
image("../assets/issues/mi-utem.png"),
caption: [Listado de Issues en #link("https://github.com/exdevutem/mi-utem/issues")[el repositorio de la app Mi Utem.]],
) <miutem-issues>
La idea de un Issue es generar una discusión de acuerdo a un problema, y buscarle una solución de manera comunitaria, así como mantener una trazabilidad de los cambios que se han ido discutiendo.
Para crear un nuevo issue, solo necesitas ingresar a la parte de issues de un repositorio de Github, y apretar en `new issue`. Dentro, un formulario te indicará el título de la propuesta, y la descripción de la misma, en la cual puedes utilizar Markdown (ver @markdown) para describir tu problema de forma organizada, al igual que incluir imágenes y otras cosas.
#figure(
grid(columns: (50%, 50%), rows: (auto), gutter: 1pt,
image("../assets/issues/markdown.png"),
image("../assets/issues/preview.png"),
),
caption: [Markdown y preview en un comentario de Issues de Github],
) <markdown>
Creada la Issue, cualquier persona que pueda ver el repo puede comentar y discutirla al respecto (ver @comments), y cualquier cambio que sea relacionado a esta es adherido a la historia lineal del foro (ver @changes).
#figure(
image("../assets/issues/comments.png"),
caption: [Comentarios hechos en un Issue de Mi Utem],
)<comments>
#figure(
image("../assets/issues/changes.png"),
caption: [Diversos cambios han sido agregados a este Issue],
)<changes>
Por último, cuando la discusión dio frutos, cuando no se llegó a ningún lado, o en general, cuando este issue termina su relevancia, puede ser cerrado de forma indefinida.
#figure(
image("../assets/issues/finished.png"),
caption: [Esta Issue ha sido resuelta.],
)<finished>
== ¿Cuándo debería levantar un Issue?
Siempre que tengas dudas! Lo ideal es que investigues en el repositorio si tu duda ya ha sido preguntada antes en primer lugar, y en caso de que no exista, no deberías nunca tener miedo de levantar la tuya propia. Si te da desconfianza, prueba molestar en los repositorios de tus amigos primero. Levantar un Issue es algo super común y esperado, y están ahí no para que critiquen un repositorio, sino para ayudarlos a mejorar.
== ¿Cuándo debería cerrar un Issue?
Cuando termine su relevancia. El caso más común es que este issue haya provocado que alguien quiera solucionarlo, y haya creado una nueva rama de trabajo, y levantado un pull request con la solución. Si el problema original que mencionaste fue resuelto, cierra tu issue!
Si el problema no fue resuelto correctamente, pero ya cerraste tu issue, tampoco hay problema. Las issues pueden ser re-abiertas si es que se nota que vuelven a ser relevantes.
|
|
https://github.com/sitandr/typst-examples-book | https://raw.githubusercontent.com/sitandr/typst-examples-book/main/src/snippets/math/numbering.md | markdown | MIT License | # Math Numbering
## Number by current heading
> See also built-in numbering in [math package section](../../packages/math.md#theorems)
```typ
/// original author: laurmaedje
#set heading(numbering: "1.")
// reset counter at each chapter
// if you want to change the number of displayed
// section numbers, change the level there
#show heading.where(level:1): it => {
counter(math.equation).update(0)
it
}
#set math.equation(numbering: n => {
numbering("(1.1)", counter(heading).get().first(), n)
// if you want change the number of number of displayed
// section numbers, modify it this way:
/*
let count = counter(heading).get()
let h1 = count.first()
let h2 = count.at(1, default: 0)
numbering("(1.1.1)", h1, h2, n)
*/
})
= Section
== Subsection
$ 5 + 3 = 8 $ <a>
$ 5 + 3 = 8 $
= New Section
== Subsection
$ 5 + 3 = 8 $
== Subsection
$ 5 + 3 = 8 $ <b>
Mentioning @a and @b.
```
## Number only labeled equations
### Simple code
```typ
// author: shampoohere
#show math.equation:it => {
if it.fields().keys().contains("label"){
math.equation(block: true, numbering: "(1)", it)
// Don't forget to change your numbering style in `numbering`
// to the one you actually want to use.
//
// Note that you don't need to #set the numbering now.
} else {
it
}
}
$ sum_x^2 $
$ dif/(dif x)(A(t)+B(x))=dif/(dif x)A(t)+dif/(dif x)B(t) $ <ep-2>
$ sum_x^2 $
$ dif/(dif x)(A(t)+B(x))=dif/(dif x)A(t)+dif/(dif x)B(t) $ <ep-3>
```
### Make the hacked references clickable again
```typ
// author: gijsleb
#show math.equation:it => {
if it.has("label") {
// Don't forget to change your numbering style in `numbering`
// to the one you actually want to use.
math.equation(block: true, numbering: "(1)", it)
} else {
it
}
}
#show ref: it => {
let el = it.element
if el != none and el.func() == math.equation {
link(el.location(), numbering(
// don't forget to change the numbering according to the one
// you are actually using (e.g. section numbering)
"(1)",
counter(math.equation).at(el.location()).at(0) + 1
))
} else {
it
}
}
$ sum_x^2 $
$ dif/(dif x)(A(t)+B(x))=dif/(dif x)A(t)+dif/(dif x)B(t) $ <ep-2>
$ sum_x^2 $
$ dif/(dif x)(A(t)+B(x))=dif/(dif x)A(t)+dif/(dif x)B(t) $ <ep-3>
In @ep-2 and @ep-3 we see equations
```
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/show-text-02.typ | typst | Other | // Test that replacements happen exactly once.
#show "A": [BB]
#show "B": [CC]
AA (8)
|
https://github.com/adam-zhang-lcps/papers | https://raw.githubusercontent.com/adam-zhang-lcps/papers/main/oscillation-modeling.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "@preview/cetz:0.2.2"
#import "@preview/unify:0.5.0": qty
#import "./aet-lab-report-template.typ": aet-lab-report
#show: doc => aet-lab-report(
title: "Investigating the Factors in a Spring System that Affect a Model of Simple Harmonic Motion",
course: "AET AP Physics C: Mechanics",
teacher: "Mr. <NAME> and Mr. <NAME>",
date: datetime(year: 2024, month: 05, day: 03),
appendix: [
Note that in the interest of printability, raw position data has been rounded to 14 digits after the decimal point.
#import table: header, cell
#let data = csv("assets/oscillation-modeling/data.csv").slice(1)
#let captions = ([control], [further initial position], [heavier mass], [stiffer spring])
#show figure: set block(breakable: true)
#let aligning(x, y) = {
if y > 1 {
if calc.even(x) {
left
} else {
right
}
} else {
center
}
}
#for i in range(0, 4) {
let trials = data.map(
r => {
for c in range(0, 3) {
import calc: round
(
r.at(0),
[#round(digits: 14, float(r.at(i * 3 + c + 1)))]
)
}
},
)
[
#figure(
caption: [Raw data from #captions.at(i) trials],
table(
columns: 6,
fill: (x, y) => if calc.even(y) and y > 1 { luma(240) } else { white },
align: aligning,
header(
..range(1, 4).map(i => cell(colspan: 2)[Trial #i]),
..([Time (s)], [Position (m)]) * 3,
),
..trials.flatten(),
),
)
#label("raw-data-" + str(i))
]
}
#figure(
caption: [GNU Octave script used for nonlinear regression],
raw(
lang: "octave",
block: true,
read("assets/oscillation-modeling/regressions.m")
)
) <octave-regression-script>
],
doc,
)
= Introduction
== Purpose
Investigate what and how factors of an oscillating spring system affect the respective parameters of a simple harmonic motion model.
== Hypothesis <hypothesis>
Starting displacement ($x_0$) and starting velocity ($v_0$) are correlated with
the amplitude ($A$) and phase shift ($Phi$) of the model. Mass ($m$) is
inversely proportional to period ($omega$). Spring stiffness ($k$) is
proportional to period ($omega$).
== Background <background>
Simple harmonic motion refers to an oscillatory motion in which the force returning the system to equilibrium---the "restoring" force---is directly proportional to the displacement of the system from said equilibrium. In this case, by Newton's 2nd Law of motion, the acceleration is directly proportional to the displacement from equilibrium @MoebsEtAl2016UniversityPhysics.
A quintessential example of simple harmonic motion, and the one investigated in this experiment, is the oscillation of an ideal spring with a weight attached. At displacements small relative to the length of the spring, ideal springs obey Hooke's Law (@hookes-law), which states that the restoring force exerted by a spring is directly proportional to the spring's displacement from equilibrium; the proportionality constant is known as the "spring constant", and relates to the stiffness of the spring @Dourmashkin2016HookesLaw.
$ F_s = -k x $ <hookes-law>
By using Newton's 2nd Law, @hookes-law can be used to derive the second-order differential equation shown in @acceleration-difeq. Solving this differential equation yields the model for position as a function of time presented in @basic-shm-model.
$ (dif^2 x)/(dif t^2) = -k/m x $ <acceleration-difeq>
$ x = A cos(omega t + Phi) $ <basic-shm-model>
As shown by @basic-shm-model, simple harmonic motion is modeled by a sinusoidal wave, where $A$ represents the amplitude of the oscillation, $omega$ represents the angular frequency, and $Phi$ represents the phase shift of the wave. As $A$ represents the amplitude of the oscillation, it represents the maximum distance away from equilibrium that the mass reaches (as $forall x in RR : cos(x) gt.not 1$), and depends solely upon the initial conditions (position and velocity). The angular frequency $omega$ is dependent upon the mass of the oscillating object and the stiffness of the spring, and is equal to $sqrt(k/m)$ @Meyers2024OscillatorKinematics. Finally, phase shift changes only the point at which the wave starts, and is also dependent solely upon initial conditions. Notably, a system with initial velocity is functionally equivalent to a system with no initial velocity and a further starting distance, and results only in a phase shift @MoebsEtAl2016UniversityPhysics.
This experiment seeks to experimentally verify the theoretical models discussed above. To do so, a mass $m_1$ will be suspended from a vertical spring of stiffness $k_1$ and allowed to oscillate from a starting position $Delta x_1$. Motion will be recorded using a Vernier Motion Sensor#emoji.reg. Two differing masses ($m_1$ and $m_2$), starting positions ($Delta x_1$ and $Delta x_2$), and springs ($k_1$ and $k_2$) will be tested, each in isolation, to determine how each change affects the resulting simple harmonic motion model.
To calculate resulting parameters for the simple harmonic motion model, a nonlinear regression will be performed using a GNU Octave#footnote([https://octave.org]) script utilizing the `optim` package#footnote([https://octave.sourceforge.io/optim]), which performs nonlinear regression using the Levenberg–Marquardt algorithm (LMA). Regression is generally performed by attempting to minimize the squares of the difference between the predicted values from a model and the actual values ($S$ in @least-squares). LMA is a method to solve the least squares problem for nonlinear models, such as simple harmonic motion. Unlike regressions with linear models, which can be solved absolutely, LMA attempts to find a minimum through iteratively descending parameters towards values that minimize the squares @Levenberg1944LeastSquares @Marquardt1963LeastSquares. This means that LMA is sensitive to the initial parameter choices---especially in cases where the model involves periodic functions, such as simple harmonic motion. For this experiment, initial parameters were set in the script to achieve the best regression results possible. Notably, phase shift ($Phi$) is especially difficult to calculate, as there are infinite possibilities (since cosine is periodic). The full script is available in the appendix in @octave-regression-script.
$ S = sum_(i=0)^n (y_i - f(x_i))^2 $ <least-squares>
= Methods
== Materials
The following materials are required for this experiment.
- Two springs of different stiffness $k_1$ and $k_2$.
- A bar to hang a spring from.
- Two differing masses $m_1$ and $m_2$.
- A computer capable of running Vernier Graphical Analysis#emoji.reg.
- A Vernier Motion Sensor#emoji.reg.
The setup for this experiment is shown in @setup and @setup-2.
#figure(
caption: [Setup of spring system in equilibrium],
)[
#cetz.canvas(
length: 20%, {
import cetz.draw: *
import cetz.decorations: *
line(stroke: 3pt, (-1.6, -1.2), (rel: (0, 2.2)))
line(stroke: 2pt, (-2, 1), (1, 1))
line(name: "x-axis", stroke: (dash: "dashed"), (-0.2, -0.2), (rel: (1, 0)))
content((rel: (-0.2, 0), to: "x-axis.start"))[$ x = 0 $]
coil(
name: "spring", amplitude: 0.25, start: 5%, end: 95%, line((0.4, 1), (rel: (0, -1))),
)
content((rel: (0.3, 0), to: "spring.mid"))[$ k $]
rect(
name: "mass", fill: white, (rel: (-0.2, -0.01), to: "spring.end"), (rel: (0.4, -0.4)),
)
content("mass")[$ m $]
rect(name: "sensor", (0.3, -1), (0.5, -1.2))
arc(
(rel: (-0.08, 0), to: "sensor.north"), start: 180deg, stop: 360deg, radius: 0.08,
)
content((rel: (-0.6, 0), to: "sensor.east"))[Motion Sensor]
line(stroke: (dash: "dotted"), "sensor.north", "mass.south")
},
)
] <setup>
#figure(
caption: [Setup of spring system before release],
)[
#cetz.canvas(
length: 20%, {
import cetz.draw: *
import cetz.decorations: *
line(stroke: 3pt, (-1.6, -1.2), (rel: (0, 2.2)))
line(stroke: 2pt, (-2, 1), (1, 1))
line(
name: "x-axis", stroke: (dash: "dashed"), (-0.2, -0.2), (rel: (0.8, 0)),
)
content((rel: (-0.2, 0), to: "x-axis.start"))[$ x = 0 $]
coil(
name: "spring", amplitude: 0.25, start: 5%, end: 95%, line((0.4, 1), (rel: (0, -1.4))),
)
content((rel: (0.3, 0), to: "spring.mid"))[$ k $]
rect(
name: "mass", fill: white, (rel: (-0.2, -0.01), to: "spring.end"), (rel: (0.4, -0.4)),
)
content("mass")[$ m $]
line(
name: "dx", (rel: (0.05, 0), to: "x-axis.end"), (rel: (0.1, 0)), (rel: (0, -0.4)), (rel: (-0.1, 0)),
)
content((rel: (0.12, 0), to: "dx.mid"))[$ Delta x $]
rect(name: "sensor", (0.3, -1), (0.5, -1.2))
arc(
(rel: (-0.08, 0), to: "sensor.north"), start: 180deg, stop: 360deg, radius: 0.08,
)
content((rel: (-0.6, 0), to: "sensor.east"))[Motion Sensor]
line(stroke: (dash: "dotted"), "sensor.north", "mass.south")
},
)
] <setup-2>
== Procedures
The following procedure was implemented during this experiment.
+ The spring system was set up in equilibrium using the spring of constant $k_1$ and mass $m_1$ (see @setup). <proc-1>
+ The mass was pulled down by #qty(5.0, "cm") ($Delta x_1$) to bring the system out of equilibrium (see @setup-2).
+ Data collection was initiated in Vernier Graphical Analysis#emoji.reg.
+ The mass was released and allowed to oscillate for the period of data
collection. <proc-2>
+ Steps #link(label("proc-1"))[1] through #link(label("proc-2"))[4] were repeated two more times to collect three total trials of data. <proc-3>
+ Steps #link(label("proc-1"))[1] through #link(label("proc-3"))[5] were repeated three more times---once with the mass pulled down #qty(7.5, "cm") ($Delta x_2$), once with the spring of constant $k_1$ and mass $m_2$, and once with the mass $m_1$ and spring of constant $k_2$.
+ Data from Vernier Graphical Analysis#emoji.reg was saved as a CSV file.
+ Regressions were fit to each set of trials matching the model for simple harmonic motion as described in #link(label("background"), [the background]).
= Results
== Data
Graphs showing the three trials of data collected for each variation as well as a line of best fit for each trial were created. @control-graph shows the results from the control trials. @initial-position-graph shows the results from the trials with a further initial position. @heavier-mass-graph shows the results from the trials with a heavier mass hanging from the spring. @stiffer-spring-graph shows the results from the trials with a stiffer spring.
The full raw data is available in the appendix in @raw-data-0, @raw-data-1, @raw-data-2, and @raw-data-3.
#let data = csv("assets/oscillation-modeling/data.csv").slice(1).map(r => r.map(float))
#let params = csv("assets/oscillation-modeling/parameters.csv").map(r => r.map(float))
#let captions = ([Control], [Further Initial Position], [Heavier Mass], [Stiffer Spring])
#let labels = ("control", "initial-position", "heavier-mass", "stiffer-spring")
#for i in range(0, 4) [
#figure(
caption: [Time vs. Position for #lower(captions.at(i)) trials],
cetz.canvas({
import cetz.draw: *
import cetz.plot: *
let data_offset = i * 3 + 1
let colors = (green, blue, red)
plot(
size: (15, 8), axis-style: "scientific-auto", legend: "legend.north", legend-style: (orientation: ltr, stroke: none), x-label: [Time (s)], y-label: [Position (m)], x-grid: "both", y-grid: "both", {
for j in range(0, 3) {
add(
style: (stroke: none),
mark: "o",
mark-size: .15,
mark-style: (stroke: none, fill: colors.at(j)),
label: [Trial #(j + 1)],
data.map(r => (r.at(0), r.at(data_offset + j))),
)
let ps = params.at(i * 3 + j)
add(
domain: (0, 5),
samples: 250,
style: (stroke: (paint: colors.at(j), dash: "dashed")),
x => ps.at(0) * calc.cos(ps.at(1) * x + ps.at(2)),
)
}
},
)
}),
)
#label(labels.at(i) + "-graph")
]
== Calculations
#let averages = range(0, 4).map(i => {
import calc: round
params.slice(i * 3, count: 3)
.fold((0, 0, 0), (acc, cur) => {
acc.zip(cur).map(((a, b)) => a + b)
})
.map(x => x / 3)
})
The above figures included lines of best fit from a nonlinear regression calculated using the model of simple harmonic motion. The values for the parameters for each regression, as well as the averages per each set of trials, are shown in @parameters. A graph showing the model for each set of trials using the average parameter values is shown in @average-parameters-graph.
#figure(
caption: [Simple harmonic motion regression parameter values (rounded to 14 decimal places)],
table(
columns: 5,
stroke: (x, y) => if x < 2 and y < 1 { none } else { 1pt },
align: (x, y) => if y > 0 and x > 1 { right } else { center },
table.header([], [], $A$, $omega$, $Phi$),
..range(0, 4).map(i => {
import calc: round
(
table.cell(rowspan: 4, align: horizon, captions.at(i)),
..range(0, 3).map(j => {
(
[Trial #(j + 1)],
..params.at(i * 3 + j)
.map(f => round(digits: 14, f))
.map(str)
)
}),
[Average],
..averages
.at(i)
.map(x => round(digits: 14, x))
.map(str)
)
}).flatten()
)
) <parameters>
#figure(
caption: [Models using average parameters],
cetz.canvas({
import cetz.plot: *
plot(
size: (15, 8), axis-style: "scientific-auto", legend: "legend.north", legend-style: (orientation: ltr, stroke: none), x-label: [Time (s)], y-label: [Position (m)], x-grid: "both", y-grid: "both", {
import calc: cos
for i in range(0, 4) {
let ps = averages.at(i)
add(
domain: (0, 5),
samples: 250,
label: captions.at(i),
x => ps.at(0) * cos(ps.at(1) * x + ps.at(2)))
}
}
)
})
) <average-parameters-graph>
= Discussion
== Conclusion
The purpose of the experiment was partially accomplished. While it was successfully determined which parameters of a simple harmonic motion model are affected by corresponding factors in a simple spring system, the exact relationship between values was not successfully proven.
By looking at the results of varying factors in @parameters and @average-parameters-graph in comparison to the control trial, relationships can be inferred. A further initial position increased the amplitude ($A$) by a significant amount. A heavier mass and stiffer spring decreased and increased the frequency of oscillation ($omega$), respectively, by a significant amount. This lines up with the predictions in #link(label("hypothesis"), [the hypothesis]) and principles discussed in #link(label("background"), [the background]).
Notably, calculated values for phase shift ($Phi$) were not consistent throughout trials. However, this can be attributed to multiple factors. The phase shift is only affected by the initial conditions of the system---the initial position and velocity. Due to inconsistencies in both the initialization of data collection and human error in holding the spring at a perfectly consistent length, these initial conditions were not constant throughout trials. Additionally, due to phase shift being a value with infinite possible values, nonlinear regressions struggle to converge to a consistent value. See #link(label("background"), [the background]) and #link(label("errors"), [the errors]) sections for more details.
== Errors <errors>
There were many sources of error present within this experiment that resulted in data not fully consistent with theoretical models.
As mentioned previously, the largest inconsistency throughout the collected data is the calculated phase shift $Phi$. This is largely attributable to inconsistencies in the starting condition of the spring system. Considering the model for simple harmonic motion (@basic-shm-model), the phase shift affects only where the sinusoidal wave begins. Thus, it is dependent only upon the starting position and velocity of the spring @MoebsEtAl2016UniversityPhysics. While every effort was made to keep the starting position at exactly #qty(5.0, "cm") or #qty(7.5, "cm") and starting velocity at exactly zero, due to the procedure being executed by humans, natural human error was present. This error is especially prevalent in @initial-position-graph and @stiffer-spring-graph. Further experimentation should attempt to minimize this error through a precise manner of controlling starting conditions.
Another source of experimental error is the failure to account for dampened motion. Simple harmonic motion accurately models an ideal system, where energy is fully conserved. Unfortunately, the real world is not an ideal system, and is subject to external factors---most notably friction and air resistance. Since the experiment was performed with a spring suspended vertically, friction is not a major concern---however, air resistance was undoubtedly present. This results in _damped_ harmonic motion. Since air resistance is dependent upon the current velocity of the object, @acceleration-difeq becomes @acceleration-damped-difq. Solving this equation yields @damped-shm-model @MoebsEtAl2016UniversityPhysics @Kreyszig1972EngineeringMathematics @Meyers2024DampedAndOtherOscillations.
$ (dif^2 x)/(dif t^2) = -k/m x - mu (dif x)/(dif t) $ <acceleration-damped-difq>
$ x = A_0 e^(-b/(2m) t) cos(omega t + Phi) $ <damped-shm-model>
As shown by @damped-shm-model, damped harmonic motion includes an exponential decay term, the speed of which is determined by the value $b$. This value represents properties of the system such as the fluid viscosity @Meyers2024DampedAndOtherOscillations. This decaying amplitude is visible in the graphs of the data collected, most visibly in @heavier-mass-graph.
Finally, an error in the design of this experiment restricted the ability to draw full conclusions. Data regarding how a change in the spring system affected the resultant model was only collected in one direction; e.g. a control mass $m_1$ and a heavier mass $m_2$ were tested, but not a lighter mass $m_3$. Additionally, the exact numerical values of the spring constants for the springs used, $k_1$ and $k_2$, were not recorded due to a lack of foresight. This restricts the conclusions that can be gathered, as a full theoretical model cannot be made.
== Extensions
Extensions to this experiment should primarily aim to fix the shortcoming discussed in the #link(label("errors"), "errors"). A more controlled environment can be used to ensure that the starting conditions of each trial are consistent so that the difference in phase shift can be accurately calculated---one way this could be accomplished is by using a reproducible mechanism to release the spring. Additionally, more trials should be performed with a larger number of variations of the characteristics of the spring system so the mathematical model for simple harmonic motion can be validated from experimental data. Finally, future experimenters may consider performing the experiment in a vacuum to negate the effects of air resistance.
Alternatively, other facets of harmonic motion can be tested, such as dampening. While air resistance is one form of damped harmonic motion, there are many other systems that experience damping, such as a spring moving through a viscous fluid, friction within vibrating solids such as a tuning fork, and the suspension system of a car. Further experimentation could extend to include data to determine the factors that affect the model of damped harmonic motion.
== Applications
Harmonic motion is present in many places, and has many real-world applications. Springs are a common example, such as in this experiment, or in the springs in a car's suspension system, which present an example of damped motion---these springs attempt to reduce the vibration resulting from road imperfections @Syakir2023HarmonicMotionCars. Another common example is pendulums, such as the pendulum in a grandfather clock, which oscillates with a period of one or two seconds to accurately track time @McCormack2017SimpleHarmonicMotionTimekeeping. A more atypical example of harmonic motion can be seen in planetary orbits---when orbits are near circular, the two axes in the plane of rotation each individually exhibit harmonic motion, as movement around a circle is sinusoidal along both axes @Tatum2022SimpleHarmonicMotion.
|
https://github.com/DannySeidel/typst-dhbw-template | https://raw.githubusercontent.com/DannySeidel/typst-dhbw-template/main/titlepage.typ | typst | MIT License | #import "locale.typ": *
#let titlepage(
authors,
date,
heading-font,
language,
left-logo-height,
logo-left,
logo-right,
many-authors,
right-logo-height,
supervisor,
title,
type-of-degree,
type-of-thesis,
university,
university-location,
at-university,
date-format,
show-confidentiality-statement,
confidentiality-marker,
university-short,
) = {
if (many-authors) {
v(-1.5em)
} else {
v(-1em)
}
// logos (optional)
stack(dir: ltr,
spacing: 1fr,
// Logo at top left if given
align(horizon,
if logo-left != none {
set image(height: left-logo-height)
logo-left
}
),
// Logo at top right if given
align(horizon,
if logo-right != none {
set image(height: right-logo-height)
logo-right
}
)
)
if (many-authors) {
v(1fr)
} else {
v(1.5fr)
}
// title
align(center, text(weight: "semibold", font: heading-font, 2em, title))
if (many-authors) {
v(0.5em)
} else {
v(1.5em)
}
// confidentiality marker (optional)
if (confidentiality-marker.display) {
let size = 7em
let display = false
let title-spacing = 2em
let x-offset = 0pt
let y-offset = if (many-authors) {
7pt
} else {
0pt
}
if (type-of-degree == none and type-of-thesis == none) {
title-spacing = 0em
}
if ("display" in confidentiality-marker) {
display = confidentiality-marker.display
}
if ("offset-x" in confidentiality-marker) {
x-offset = confidentiality-marker.offset-x
}
if ("offset-y" in confidentiality-marker) {
y-offset = confidentiality-marker.offset-y
}
if ("size" in confidentiality-marker) {
size = confidentiality-marker.size
}
if ("title-spacing" in confidentiality-marker) {
confidentiality-marker.title-spacing
}
v(title-spacing)
let color = if (show-confidentiality-statement) {
red
} else {
green.darken(5%)
}
place(
right,
dx: 35pt + x-offset,
dy: -70pt + y-offset,
circle(radius: size / 2, fill: color),
)
}
// type of thesis (optional)
if (type-of-thesis != none and type-of-thesis.len() > 0) {
align(center, text(weight: "semibold", 1.25em, type-of-thesis))
v(0.5em)
}
// type of degree (optional)
if (type-of-degree != none and type-of-degree.len() > 0) {
align(center, text(1em, TITLEPAGE_SECTION_A.at(language)))
v(-0.25em)
align(center, text(weight: "semibold", 1.25em, type-of-degree))
}
v(1.5em)
// course of studies
align(
center,
text(
1.2em,
TITLEPAGE_SECTION_B.at(language) + authors.map(author => author.course-of-studies).dedup().join(" | "),
),
)
if (many-authors) {
v(0.75em)
} else {
v(1em)
}
// university
align(
center,
text(
1.2em,
TITLEPAGE_SECTION_C.at(language) + university + [ ] + university-location,
),
)
if (many-authors) {
v(0.8em)
} else {
v(3em)
}
align(center, text(1em, BY.at(language)))
if (many-authors) {
v(0.8em)
} else {
v(2em)
}
// authors
grid(
columns: 100%,
gutter: if (many-authors) {
14pt
} else {
18pt
},
..authors.map(author => align(
center,
{
text(weight: "medium", 1.25em, author.name)
},
))
)
if (many-authors) {
v(0.8em)
} else {
v(2em)
}
// date
align(
center,
text(
1.2em,
if (type(date) == datetime) {
date.display(date-format)
} else {
date.at(0).display(date-format) + [ -- ] + date.at(1).display(date-format)
},
),
)
v(1fr)
// author information
grid(
columns: (auto, auto),
row-gutter: 11pt,
column-gutter: 2.5em,
// students
text(weight: "semibold", TITLEPAGE_STUDENT_ID.at(language)),
stack(
dir: ttb,
for author in authors {
text([#author.student-id, #author.course])
linebreak()
}
),
// company
if (not at-university) {
text(weight: "semibold", TITLEPAGE_COMPANY.at(language))
},
if (not at-university) {
stack(
dir: ttb,
for author in authors {
let company-address = ""
// company name
if (
"name" in author.company and
author.company.name != none and
author.company.name != ""
) {
company-address+= author.company.name
} else {
panic("Author '" + author.name + "' is missing a company name. Add the 'name' attribute to the company object.")
}
// company address (optional)
if (
"post-code" in author.company and
author.company.post-code != none and
author.company.post-code != ""
) {
company-address+= text([, #author.company.post-code])
}
// company city
if (
"city" in author.company and
author.company.city != none and
author.company.city != ""
) {
company-address+= text([, #author.company.city])
} else {
panic("Author '" + author.name + "' is missing the city of the company. Add the 'city' attribute to the company object.")
}
// company country (optional)
if (
"country" in author.company and
author.company.country != none and
author.company.country != ""
) {
company-address+= text([, #author.company.country])
}
company-address
linebreak()
}
)
},
// company supervisor
if ("company" in supervisor) {
text(weight: "semibold", TITLEPAGE_COMPANY_SUPERVISOR.at(language))
},
if ("company" in supervisor and type(supervisor.company) == str) {
text(supervisor.company)
},
// university supervisor
if ("university" in supervisor) {
text(
weight: "semibold",
TITLEPAGE_SUPERVISOR.at(language) +
university-short +
[:]
)
},
if ("university" in supervisor and type(supervisor.university) == str) {
text(supervisor.university)
}
)
} |
https://github.com/ckunte/m-one | https://raw.githubusercontent.com/ckunte/m-one/master/inc/wavelength.typ | typst | = Wave length
This is a script I have had to write at different times and in different tools in the past --- either to figure out the depth type or when requiring appropriate wave length(s) to calculate hydrostatic pressure. Here's hoping this will be the last.
For background, dispersion relation#footnote[Dispersion relation (eq. 24), Wave and Wave Effects (pp. 240--246), <NAME>, Marine Hydrodynamics, The MIT Press, 1977.@newman_1977], which expresses wave length ($lambda$)#footnote[$lambda$ is not to be confused with _lambda_ the anonymous function in python programming language.@lutz_2013] in terms of wave number ($kappa = 2pi / lambda$) and angular wave frequency ($omega = 2pi / T$) is as follows:
$ omega^2 / g = kappa tanh(kappa d) $
When $lim_(arrow.r oo) tanh(k d) tilde.eq 1$, it reduces the expression to:
$ lambda = 2pi g / omega^2 $
For practical purposes, water depth (d) is considered deep when $d / lambda gt.eq 0.5$. In other words,
$ lambda_d = 2pi g / omega^2 = g T^2 / 2pi $
For shallow water depth (i.e., $d / lambda eq.lt 0.05$), wave length is expressed as:
$ lambda_s = T sqrt(g d) $
This is because $lim_(arrow.r oo) tanh(k d) tilde.eq k d$. For intermediate water depth (i.e., $0.05 < d / lambda < 0.5$), wave length can be expressed as:
$ lambda_i = lambda_d sqrt(tanh( 2pi d / lambda_d)) $
Turning this above into code for a list of wave periods:
#let wavelength = read("/src/wavelength.py")
#{linebreak();raw(wavelength, lang: "python")}
When run, it produces this:
```bash
$ python3 wavelength.py
Water depth: 171.18
Wave periods: [9.4, 11.5, 12.0]
Water depth type (by majority): Deep
Wave length, Ld: [137.95735086939, 206.483246406490, 224.828638809335]
```
$ - * - $ |
|
https://github.com/unforswearing/typst_invoice | https://raw.githubusercontent.com/unforswearing/typst_invoice/main/invoice_tmpl.typ | typst | // parameters that can be updated are stored in invoice_data.json
#let data = json("invoice_data.json")
#set document(
author: data.payable.org,
date: auto
)
#set page(
"us-letter",
fill: rgb("#F5F5EF")
)
#set text(font: "Helvetica Neue")
// -------------------------------
#show link: underline
// Invoice Parameters ----------------------------
#let invnumber = [#data.invnumber]
#let invperiod = [#data.invperiod]
#let desc = [#data.desc]
#let hours = data.hours
// Variables and Functions -----------------------
#let rate = data.rate
#let total = hours * rate
#let period = text(weight: "bold")[#invperiod]
#let inv = align(end)[
#pad(top: -10pt, bottom: -5pt)[ID: \#00#invnumber]
]
// --------------------------------------------
// Set document title using invoice information
#set document(title: [
#data.payable.org Contracting Invoice: \#00#invnumber - #invperiod - \$#total
])
// --------------------------------------------
#let today = {
align(end)[#datetime.today().display()]
}
#let separator(width) = {
line(length: 100%, stroke: width)
}
// BEGIN INVOICE ----------------------------------
#align(end)[
#text(40pt, weight: "black")[INVOICE]
]
#pad(top: -30pt, bottom: 50pt)[
#inv
#today
]
#text(weight: "black")[BILLED TO:] \
#text()[
#data.billto.org \
#data.billto.ref
]
#pad(top: 50pt)[#period]
#pad(bottom: -10pt)[#separator(1pt)]
#table(
columns: (60%, 13%, 13%, 13%),
stroke: 0pt,
inset: 10pt,
gutter: 1pt,
align: (left, center, center, right),
table.header(
[*Work*],
[*Hours*],
[*Rate*],
[*Total*]
)
)
#pad(top: -10pt, bottom: -5pt)[#separator(0.25pt)]
#table(
columns: (60%, 13%, 13%, 13%),
stroke: 0pt,
inset: 12pt,
gutter: 1pt,
align: (left, center, center, right),
table.header(
[#desc],
[#hours],
[\$#rate],
[\$#total]
)
)
#pad(top: -10pt)[#separator(1pt)]
#align(end)[#text(16pt, weight: "black")[Total: \$#total]]
#pad(top: 50pt)[]
#align(end)[
#text(weight: "black")[PAYABLE TO:] \
#text()[
#data.payable.org \
#data.payable.ref
]
] |
|
https://github.com/benjamineeckh/kul-typst-template | https://raw.githubusercontent.com/benjamineeckh/kul-typst-template/main/src/core/component/keywords.typ | typst | MIT License | #let insert-keywords(keywords, lang:"en") = {
// Keywords
if keywords != none {
heading(
level: 1,
numbering: none,
outlined: true,
if lang == "en" {
"Nomenclature"
} else {
"<NAME>"
}
)
keywords
pagebreak(weak: true)
}
} |
https://github.com/ClazyChen/Table-Tennis-Rankings | https://raw.githubusercontent.com/ClazyChen/Table-Tennis-Rankings/main/history/2018/MS-06.typ | typst |
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Men's Singles (1 - 32)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[1], [<NAME>], [CHN], [3682],
[2], [<NAME>], [CHN], [3520],
[3], [XU Xin], [CHN], [3344],
[4], [<NAME>], [GER], [3273],
[5], [<NAME>], [CHN], [3197],
[6], [OVTCHAROV Dimitrij], [GER], [3140],
[7], [MIZUTANI Jun], [JPN], [3113],
[8], [<NAME>], [CHN], [3110],
[9], [<NAME>], [CHN], [3099],
[10], [<NAME>], [CHN], [3094],
[11], [<NAME>], [KOR], [3083],
[12], [<NAME>], [BRA], [3083],
[13], [<NAME>], [SWE], [3071],
[14], [<NAME>], [CHN], [3065],
[15], [JEOUNG Youngsik], [KOR], [2994],
[16], [PITCHFORD Liam], [ENG], [2990],
[17], [<NAME>], [CHN], [2988],
[18], [<NAME> Su], [KOR], [2982],
[19], [<NAME>], [JPN], [2982],
[20], [<NAME>], [JPN], [2961],
[21], [YOSHIMURA Maharu], [JPN], [2944],
[22], [CHO Seungmin], [KOR], [2927],
[23], [UEDA Jin], [JPN], [2925],
[24], [<NAME>], [IND], [2920],
[25], [WANG Yang], [SVK], [2915],
[26], [YOSHIDA Masaki], [JPN], [2915],
[27], [WONG Chun Ting], [HKG], [2914],
[28], [#text(gray, "YOSHIDA Kaii")], [JPN], [2913],
[29], [YU Ziyang], [CHN], [2905],
[30], [<NAME>], [FRA], [2902],
[31], [ARUNA Quadri], [NGR], [2902],
[32], [GACINA Andrej], [CRO], [2894],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Men's Singles (33 - 64)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[33], [LIM Jonghoon], [KOR], [2892],
[34], [WANG Chuqin], [CHN], [2887],
[35], [NIWA Koki], [JPN], [2887],
[36], [<NAME>], [GER], [2885],
[37], [KOU Lei], [UKR], [2884],
[38], [SAMSONOV Vladimir], [BLR], [2880],
[39], [<NAME>], [JPN], [2877],
[40], [<NAME>], [GER], [2872],
[41], [XU Chenhao], [CHN], [2871],
[42], [<NAME>], [DEN], [2870],
[43], [<NAME>], [AUT], [2869],
[44], [<NAME>], [FRA], [2868],
[45], [ZHU Linfeng], [CHN], [2867],
[46], [<NAME>], [SWE], [2864],
[47], [ZHOU Qihao], [CHN], [2862],
[48], [<NAME>], [SLO], [2856],
[49], [<NAME>], [JPN], [2851],
[50], [#text(gray, "<NAME>")], [QAT], [2840],
[51], [<NAME>], [CHN], [2839],
[52], [<NAME>], [POR], [2834],
[53], [<NAME>], [HUN], [2829],
[54], [#text(gray, "CHEN Weixing")], [AUT], [2826],
[55], [SHIBAEV Alexander], [RUS], [2826],
[56], [<NAME>], [IRI], [2826],
[57], [<NAME>], [GER], [2823],
[58], [SKACHKOV Kirill], [RUS], [2818],
[59], [<NAME>], [GER], [2817],
[60], [<NAME>], [TPE], [2814],
[61], [<NAME>], [KOR], [2804],
[62], [<NAME>], [SWE], [2803],
[63], [<NAME>], [TPE], [2798],
[64], [XUE Fei], [CHN], [2796],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Men's Singles (65 - 96)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[65], [OIKAWA Mizuki], [JPN], [2795],
[66], [IONESCU Ovidiu], [ROU], [2789],
[67], [KIM Donghyun], [KOR], [2785],
[68], [ZHOU Kai], [CHN], [2782],
[69], [<NAME>], [GER], [2775],
[70], [GERASSIMENKO Kirill], [KAZ], [2768],
[71], [APOLONIA Tiago], [POR], [2766],
[72], [<NAME>], [SLO], [2765],
[73], [MURAMATSU Yuto], [JPN], [2761],
[74], [TSUBOI Gustavo], [BRA], [2758],
[75], [FEGERL Stefan], [AUT], [2758],
[76], [WANG Eugene], [CAN], [2758],
[77], [GERELL Par], [SWE], [2752],
[78], [PISTEJ Lubomir], [SVK], [2750],
[79], [KIM Minhyeok], [KOR], [2745],
[80], [WANG Zengyi], [POL], [2743],
[81], [GIONIS Panagiotis], [GRE], [2739],
[82], [ZHMUDENKO Yaroslav], [UKR], [2739],
[83], [MOREGARD Truls], [SWE], [2738],
[84], [CHUANG Chih-Yuan], [TPE], [2737],
[85], [OSHIMA Yuya], [JPN], [2737],
[86], [#text(gray, "MATTENET Adrien")], [FRA], [2735],
[87], [TAKAKIWA Taku], [JPN], [2732],
[88], [DESAI Harmeet], [IND], [2731],
[89], [ASSAR Omar], [EGY], [2727],
[90], [ZHAI Yujia], [DEN], [2714],
[91], [LUNDQVIST Jens], [SWE], [2710],
[92], [JIANG Tianyi], [HKG], [2704],
[93], [STOYANOV Niagol], [ITA], [2702],
[94], [PAK Sin Hyok], [PRK], [2701],
[95], [AN Jaehyun], [KOR], [2700],
[96], [KIZUKURI Yuto], [JPN], [2698],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Men's Singles (97 - 128)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[97], [HO Kwan Kit], [HKG], [2698],
[98], [MACHI Asuka], [JPN], [2696],
[99], [PARK Ganghyeon], [KOR], [2696],
[100], [MINO Alberto], [ECU], [2695],
[101], [UDA Yukiya], [JPN], [2694],
[102], [KIM Minseok], [KOR], [2691],
[103], [<NAME>], [SWE], [2688],
[104], [<NAME>], [POR], [2688],
[105], [<NAME>], [USA], [2686],
[106], [<NAME>], [KOR], [2683],
[107], [#text(gray, "ELOI Damien")], [FRA], [2683],
[108], [<NAME>], [KOR], [2683],
[109], [#text(gray, "FANG Yinchi")], [CHN], [2681],
[110], [LIVENTSOV Alexey], [RUS], [2681],
[111], [<NAME>], [AUT], [2675],
[112], [<NAME>], [ALG], [2675],
[113], [<NAME>], [JPN], [2671],
[114], [<NAME>], [FRA], [2670],
[115], [<NAME>], [CZE], [2665],
[116], [ECSEKI Nandor], [HUN], [2662],
[117], [<NAME>], [JPN], [2660],
[118], [<NAME>], [TUR], [2659],
[119], [<NAME>], [ESP], [2659],
[120], [MATSUYAMA Yuki], [JPN], [2659],
[121], [<NAME>], [CZE], [2659],
[122], [<NAME>], [PAR], [2657],
[123], [<NAME>], [JPN], [2655],
[124], [<NAME> Hang], [HKG], [2654],
[125], [QIU Dang], [GER], [2653],
[126], [WALKER Samuel], [ENG], [2649],
[127], [GAO Ning], [SGP], [2648],
[128], [SEYFRIED Joe], [FRA], [2646],
)
) |
|
https://github.com/Daillusorisch/HYSeminarAssignment | https://raw.githubusercontent.com/Daillusorisch/HYSeminarAssignment/main/template/components/cover.typ | typst | #import "../utils/style.typ": *
#let cover(
title: "",
author: "",
student-id: "",
major: "",
school: "",
supervisor: "",
date: ""
) = {
align(center)[
#v(62pt)
#let logo = "../assets/whu.png"
#image(logo, width: 33%, height: 10%, fit: "contain")
#text(
size: 字号.二号,
font: 字体.宋体,
weight: "bold"
)[本科课程作业]
#v(59pt)
#text(
size: 字号.一号,
font: 字体.楷体,
title
)
#v(86pt)
#let info_block(content) = {
text(
font: 字体.宋体,
size: 字号.四号,
content
)
}
#grid(
columns: (70pt, 150pt),
rows: (32pt, 32pt),
info_block("姓 名:"),
info_block(author),
info_block("学 号:"),
info_block(student-id),
info_block("专 业:"),
info_block(major),
info_block("学 院:"),
info_block(school),
info_block("指导教师:"),
info_block(supervisor)
)
#place(
bottom + center,
float: true,
text(
font: 字体.宋体,
size: 字号.四号,
spacing: 150%,
date
)
)
#pagebreak(weak: true)
]
}
|
|
https://github.com/konradroesler/lina-skript | https://raw.githubusercontent.com/konradroesler/lina-skript/main/lina-1.typ | typst | #import "utils.typ": *
#import "template.typ": uni-script-template
#import "@preview/tablex:0.0.7": tablex, gridx, hlinex, vlinex, colspanx, rowspanx
#show: doc => uni-script-template(
title: [Vorlesungsskript],
author: [<NAME>],
module-name: [LinA I\* WiSe 23/24],
doc
)
= Motivation und mathematische Grundlagen
Was ist lineare Algebra bzw. analytische Geometrie?
#boxedlist[analytische Geometrie: \ Beschreibung von geometrischen Fragen mit Hilfe von Gleichungen, Geraden, Ebenen sowie die Lösungen von Gleichungen als geometrische Form][lineare Algebra: \ die Wissenschaft der linearen Gleichungssysteme bzw der Vektorräume und der linearen Abbildungen zwischen ihnen]
Wozu braucht man das?
#boxedlist([mathematische Grundlage für viele mathematische Forschung z.B. in der algebraischen Geometrie, Numerik, Optimierung], [viele Anwendungen z.B. Page-Rank-Algorithmus, lineare Regression], [oder Optimierung: \ linear: Beschreibung zulässiger Punkte als Lösung von (Un)-Gleichungen \ nichtlinear: notwendige Optimalitätsbedingungen])
== Mengen
Der Mengenbegriff wurde von Georg Cantor (dt. Mathematiker, 1845-1918) eingeführt.
#definition("1.1", "Mengen")[
Unter einer #bold[Menge] verstehen wir jede Zusammenfassung $M$ von bestimmten, wohlunterschiedenen Objekten $x$ unserer Anschauung oder unseres Denkens, welche #bold[Elemente] von $M$ genannt werden, zu einem Ganzen.
] <def>
#underline("Bemerkungen"):
Für jedes Objekt $x$ kann man eindeutig feststellen, ob es zu einer Menge $M$ gehört oder nicht.
$
x in M arrow x #[ist Element von] M \
x in.not M arrow x #[ist nicht Element von] M
$
#pagebreak()
#bold[Beispiel 1.2:] Beispiel für Mengen
#boxedlist([{rot, gelb, grün}], [{1, 2, 3, 4}], [$NN = {1, 2, 3, ...}, NN_0 = {0, 1, 2, 3, ...}$], [$ZZ = {..., -1, 0, 1, ...}$], [$QQ = {x | x = a/b #[mit] a in ZZ #[und] b in NN}$], [$RR = {x | x #[ist reelle Zahl]}$], [$emptyset #[bzw.] {} corres #[leere Menge]$])
#definition("1.3", "Teilmenge")[
Seien $M, N$ Mengen. \
1. $M$ heißt #bold[Teilmenge] von $N$, wenn jedes Element von $M$ auch Element von $N$ ist. \ Notation: $M subset.eq N$
2. $M$ und $N$ heißen gleich, wenn $M subset.eq N$ und $N subset.eq M$ gilt. \ Notation $M = N$ \ Falls das nicht gilt, schreiben wir $M != N$
$M$ heißt #bold[echte Teilmenge] von $N$, wenn $M subset.eq N$ und $M != N$ gilt. \ Notation: $M subset N$
] <def>
Nutzt man die Aussagenlogik, kann man diese Definitionen Umformulieren zu:
#align(center, [#boxedlist([$M subset.eq N <==> ( forall x: x in M ==> x in N )$], [$M = N <==> (M subset.eq N and N subset.eq M) wide$], [$M subset N <==> (M subset.eq N and M != N) wide$])])
#underline("Kommentare"):
#boxedlist([$<==>$ heißt "genau dann, wenn"], [$forall$ heißt "für alle"], [$and$ heißt "und"], [$:$ heißt "mit der Eigenschaft"])
#bold[Satz 1.4:] Für jede Menge $M$ gilt:
#align(center, box(width: 80%, height: auto, table(
columns: (1fr, 1fr, 1fr),
align: left,
stroke: none,
[1) $M subset.eq M$],
[2) $emptyset subset.eq M$],
[3) $M subset.eq emptyset ==> M = emptyset$]
)))
#italic[Beweis:]
zu 1) Direkter Beweis (verwenden der Definitionen um Aussage zu folgern). Die Aussage:
$
x in M ==> x in M
$
folgt aus Def. 1.1. Daraus folgt aus Def 1.3, 1, dass $M subset.eq M$.
zu 2) Widerspruchsbeweis \ Beweis der Aussage durch Annahme des Gegenteils und Herleitung eines Widerspruchs. Annahme: Es existiert eine Menge $M$, sodass $emptyset subset.eq.not M$. Dann gilt: es existiert ein $x in emptyset$ mit $x in.not M$. \ Aber: Die leere Menge enthält keine Elemente $==> op(arrow.zigzag)$ $==>$ Es existiert keine Menge $M$ mit $emptyset subset.eq.not M ==>$ Behauptung
zu 3) Nach 2. $emptyset subset.eq M$, wir wissen $M subset.eq emptyset$. Nach Def. 1.3, 2 $==> M = emptyset$
#endproof
#bold[Beispiel 1.5:] Ob ein Objekt ein Element oder eine Teilmenge einer Mengen ist, ist vom Kontext abhängig. Betrachten wir folgende Menge:
$
M := {NN, ZZ ,QQ, RR}
$
D.h. die Elemente dieser Menge $M$ sind die natürlichen, ganzen, rationalen und reellen Zahlen. Damit gilt $NN in M$ aber $NN subset ZZ$ und $NN subset QQ$.
#definition("1.6", "Mengenoperationen")[
Seien $M,N$ Mengen.
1. Man bezeichnet die Menge der Elemente, die sowhol in $M$ als auch in $N$ enthalten sind, als #bold[Durchschnitt] von $M$ und $N$
$
M sect N = {x | (x in M) and (x in N)}
$
2. Man bezeichnet die Menge der Elemente, die entweder in $M$ oder in $N$ enthalten sind oder in beiden enthalten sind, als #bold[Vereinigung] von $M$ und $N$
$
M union N = {x | (x in M) or (x in N)}
$
3. Man bezeichnet die Menge der Elemente, die in $M$ aber nicht in $N$ enthalten sind, als #bold[Differenz] von $M$ und $N$
$
M backslash N &= {x | (x in M) and (x in.not N)} \
&= {x in M | x in.not N}
$
] <def>
#bold[Beispiel 1.7:]
Für $-NN := {-n | n in NN}$ gilt:
#boxedlist([$NN union -NN = ZZ backslash {0}$], [$NN sect -NN = emptyset$])
Wichtiges Beispiel für Mengen sind Intervalle reeller Zahlen
$
[a,b] := {x in RR | a <= x <= b}, a,b in RR, a <= b
$
Dies nennt man ein abgeschlossenes Intervall (die Grenzen sind enthalten). Sei jetzt $a,b in RR, a <= b$
$
[a,b[ space.sixth := {x in RR | a <= x < b} #[oder] space.quarter ]a,b] := {x in RR | a < x <= b}
$
Diese Intervalle nennt man halboffene Intervalle (genau eine der Grenzen ist enthalten). Das Intervall
$
]a, b[ := {x in RR | a < x < b}
$
heißt offenes Intervall (keine der Grenzen ist enthalten).
Für $M := {4, 6, 8}$ und $N := {8, 10}$ gilt:
#boxedlist([$M union N = {4, 6, 8, 10}$], [$M sect N = {8}$], [$M backslash N = {4, 6}$], [$N backslash M = {10}$])
#bold[Satz 1.8:] Für zwei Mengen $M, N$ gelte $M subset.eq N$. Dann sind folgende Aussagen äquivalent:
#align(center, box(width: 80%, height: auto, table(
columns: (1fr, 1fr),
align: center,
stroke: none,
[1) $M subset N$],
[2) $N backslash M != emptyset$],
)))
#italic[Beweis:]
Behauptung: $1) <==> 2)$
zu zeigen: $1) ==> 2)$ und $2) ==> 1)$
$1) ==> 2)$: Es gilt: $M != N$. Dann existiert $x in N$ mit $x in.not M$. Dann gilt $x in N backslash M$. Also $N backslash M != emptyset$.
$2) ==> 1)$: Es gilt $N backslash M != emptyset$. Dann existiert ein $x in N$ mit $x in.not M$. Daher gilt $N != M$. Es gilt außerdem: $M subset.eq N$. Daraus folgt $M subset N$.
#endproof
#bold[Satz 1.9:] Seien $M, N, L$ Mengen. Dann gelten folgende Aussagen:
1. $M sect N subset.eq M #[und] M subset.eq M union N$
2. $M backslash N subset.eq M$
3. Kommutativgesetze: \
#align(center, [$M sect N = N sect M #[und] M union N = N union M$])
4. Assoziativgesetze: \
#align(center, [
$M sect (N sect L) = (M sect N) sect L$ \
$M union (N union L) = (M union N) union L$
])
5. Distributivgesetze: \
#align(center, [
$M union (N sect L) = (M union N) sect (M union L)$ \
$M sect (N union L) = (M sect N) union (M sect L)$ \
$M backslash (N sect L) = (M backslash N) union (M backslash L)$ \
$M backslash (N union L) = (M backslash N) sect (M backslash L)$
])
#italic[Beweis:] Es gilt $x in M sect N$ genau dann, wenn $x in M and x in N$. Die Konjunktion zweier Aussagen ist symmetrisch bezüglich der Aussage. D.h. $A and B <==> B and A$. Es gilt also
$
(x in M) and (x in N) <==> (x in N) and (x in M)
$
Verwenden wir die Definition der Schnittmenge (1.6) so erhalten wir
$
(x in N) and (x in M) <==> x in N sect M
$
Aus der Kette der Äquivalenzumformungen folgt $M sect N = N sect M$.
#endproof
Etwas kompakter für das erste Distributivgesetz:
$
x in M union (N sect L) &<==> (x in M) or (x in N union L) \
&<==> (x in M) or ((x in N) and (x in L)) \
&<==> (x in M or x in N) and (x in M or x in L) \
&<==> (x in M union N) and (x in M union L) \
&<==> x in (M union N) sect (M union L)
$
Damit ist $M union (N sect L) = (M union N) sect (M union L)$.
#endproof
Die übrigen Aussagen zeigt man analog. #italic[Übung]
Damit ist $M union N union L$ für die Mengen $M, N, L$ wohldefiniert. Dies kann auf "viele" Mengen verallgemeinert werden:
Ist $I != emptyset$ eine Menge und ist für jedes $i in I$ eine Menge $M_i$ gegeben, dann sind:
$
union.big_(i in I) M_i := {x | exists i in I #[mit] x in M_i} \
\
sect.big_(i in I) M_i := {x | forall i in I #[mit] x in M_i}
$
Die Menge I heißt auch #bold[Indexmenge]. Für $I = {1, ..., n}$ verwendet man auch die Notation
$
union.big_(i = 1)^n M_i := {x | exists i in I #[mit] x in M_i} \
\
sect.big_(i = 1)^n M_i := {x | forall i in I #[mit] x in M_i}
$
#definition("1.10", "Kardinalität, Potenzmenge")[
Sei $M$ eine endliche Menge, d.h. $M$ enthält endlich viele Elemente.
Die #bold[Mächtigkeit] oder #bold[Kardinalität] von $M$, bezeichnet mit $|M| #[oder] \#M$ ist die Anzahl von Elementen in $M$.
Die #bold[Potenzmenge] von $M$, bezeichnet mit $cal(P)(M)$ ist die Menge aller Teilmengen von $M$.
D.h.
$
cal(P)(M) := {N | N subset.eq M}
$
] <def>
#bold[Beispiel 1.11:]
Die leere Menge $emptyset$ hat die Kardinalität Null. Es gilt $cal(P)(emptyset) = {emptyset}, abs(cal(P)(emptyset)) = 1$.
Für $M = {2, 4, 6}$ gilt $abs(M) = 3$. $cal(P)(M) = {emptyset, {2}, {4}, {6}, {2, 4}, {2, 6}, {4, 6}, {2, 4, 6}}$.
Man kann zeigen: $abs(cal(P)(M)) = 2^(abs(M))$. Deswegen wird auch die Notation $2^M$ für die Potenzmenge von $M$ verwendet.
== Relationen
#definition("1.12", "Kartesisches Produkt")[
Sind $M$ und $N$ zwei Mengen, so heißt die Menge
$
M times N := {(x, y) | x in M and y in N}
$
das #bold[kartesische Produkt] von $M$ und $N$.
Sind $n$ Mengen $M_1, ..., M_n$ gegeben, so ist deren kartesisches Produkt gegeben druch:
$
M_1 times ... times M_n := {(x_1, ..., x_n) | x_1 in M_1 and ... and x_n in M_n}
$
Das n-fache kartesische Produkt einer Menge von $M$ ist:
$
M^n := M times ... times M := {(x_1, ..., x_n) | x_i in M #[für] i = 1, ..., n}
$
Ein Element $(x, y) in M times N$ heißt geordnetes Paar und eine Element $(x_1, ..., x_n) in M_1 times ... times M_n$ heißt #bold[(geordnetes) n-Tupel].
] <def>
Ist mindestens eine der auftretenden Mengen leer, so ist auch das resultierende kartesische Produkt leer, d.h. die leere Menge. Das kartesische Produkt wurde nach <NAME> benannt. <NAME> war ein französische Mathematiker (1596-1650) und ein Begründer der analytischen Geometrie.
#bold[Beispiel 1.13:] Das kartesische Produkt zweier Intervalle.
Seien $[a, b] subset RR$ und $[c, d] subset RR$ zwei abgeschlossene Intervalle von reellen Zahlen. Dann ist das kartesische Produkt beider Intervalle gegeben durch:
$
[a,b] times [c,d] := {(x, y) | x in [a,b] and y in [c,d]}
$
Das kartesische Produkt ist nicht kommutativ. Beweis durch Gegenbeispiel.
#definition("1.14", "Relationen")[
Seien $M$ und $N$ nichtleere Mengen. Eine Menge $R subset.eq M times N$ heißt #bold[Relation] zwischen $M$ und $N$. Ist $M = N$, so nennt man $R$ #bold[Relation auf $M$]. Für $(x, y) in R$ schreibt man $x attach(tilde, br: R) y$ oder $x tilde y$, wenn die Relation aus dem Kontext klar ist. Ist mindestens eine der beiden Mengen leer, dann ist auch jede Relation zwischen den beiden Mengen die leere Menge.
] <def>
#bold[Beispiel 1.15:] Sei $M = NN$ und $N = ZZ$. Dann ist
$
R := {(x, y) in M times N | x + y = 1}
$
eine Relation zwischen $M$ und $N$. Es gilt
$
R = {(1,0),(2,-1),(3,-2),...} = {(n, -n + 1) | n in NN}
$
#definition("1.16", "reflexiv, symmetrisch, antisymmetrisch, transitiv")[
Es sei $M$ eine nicht leere Menge. Eine Relation auf $M$ heißt:
#box(width: 100%, inset: (top:2.5mm, right: 0.5cm, left: 0.5cm), [
#bold[1. reflexiv:]
#v(-2mm)
$
forall x in M: x tilde x
$
#bold[2. symmetrisch:]
#v(-2mm)
$
forall x,y in M: x tilde y ==> y tilde x
$
#bold[3. antisymmetrisch:]
#v(-2mm)
$
forall x,y in M: x tilde y and y tilde x ==> x = y
$
#bold[4. transitiv:]
#v(-2mm)
$
forall x,y,z in M: x tilde y and y tilde z ==> x tilde z
$
])
] <def>
Falls die Relation $R$ reflexiv, transitiv und symmetrisch ist, so nennt man $R$ eine #bold[Äquivalenzrelation] auf $M$. Ist $R$ reflexiv, transitiv und antisymmetrisch, so nennt man $R$ eine #bold[partielle Ordnung] auf $M$.
#bold[Beispiel 1.17:] $M = RR$
#boxedlist([Die Relation $<$ auf $M = RR$ ist transitiv, aber weder reflexiv noch symmetrisch und auch nicht antisymmetrisch.],[Die Relation $<=$ auf $M = RR$ ist reflexiv, antisymmetrisch und transitiv. Sie ist nicht symmetrisch. $<=$ ist somit eine partielle Ordnung.],[Die Relation $=$ auf $RR$ ist reflexiv, symmetrisch und transitiv. Also ist $=$ eine Äquivalenzrelation. (Äquivalenzrelationen können auch antisymmetrisch sein)])
#bold[Beispiel 1.18:] Interpretiert man "Pfeile" als Objekte mit gleicher Orientierung und Länge, erhält man die Äquivalenzrelation
$
x tilde y :<==> #[$x$ und $y$ haben die gleiche Länge und Orientierung]
$
Auf Grund der Transitivität sind somit alle Pfeile einer vorgegebenen Orientierung und Länge äquivalent zu dem Pfeil, der im Koordinatenursprung startet und die gleiche Länge sowie Orientierung besitzt. Somit können wir Vektor $x = (x_1, x_2) in RR^2$ als Repräsentant einer ganzen Klasse von Pfeilen interpretieren. Alle zueinander äquivalente Pfeile haben gemeinsam, dass die Differenz zwischen End- und Anfangspunkt genau den Vektor $x$ ergeben.
Als Formalisierung erhält man:
#definition("1.19", "Äquivalenzklassen, Quotientenmenge")[
Sei $tilde$ eine Äquivalenzrelation auf einer nichtleeren Menge $M$. Die Äquivalenzklasse eines Element $overline(a) in M$ ist definiert durch:
$
[overline(a)] := {a in M | a tilde overline(a)}
$
Ist die Relation nicht aus dem Kontext klar, schreibt man $[overline(a)]_tilde$.
Elemente einer Äquivalenzklasse werden als #bold[Vertreter] oder #bold[Repräsentanten] der Äquivalenzklasse bezeichnet. Die Menge aller Äquivalenzklassen einer Äquivalenzrelation $tilde$ in einer Menge $M$, d.h.
$
M \/ tilde #h(1.5mm) := {[a]_tilde | a in M}
$
wird als #bold[Faktormenge] oder #bold[Quotientenmenge] bezeichnet.
] <def>
#bold[Beispiel 1.20:] #italic[(Fortsetzung von Beispiel 1.18)]
Die Menge aller Pfeile gleicher Länge und Orientierung bilden eine solche Äquivalenzklasse, welche durch den Vektor $x = (x_1, x_2) in RR^2$ repräsentiert wird. Die Menge der Vektoren $x = (x_1, x_2) in RR^2$ bilden die Quotientenklasse.
#bold[Beispiel 1.21:] Für eine gegebene Zahl $x in NN$ ist die Menge:
$
R_n := {(a, b) in ZZ^2 | a - b #[ist ohne Rest durch $n$ teilbar]}
$
eine Äquivalenzrelation auf $ZZ$, denn
#boxedlist([
reflexiv: $a tilde a, (a, a) in R_n :<==> a - a = 0 space checkmark$
], [
symmetrie: \
#v(0.5mm)
$a tilde b ==> (a, b) in R_n ==> a - b #[ist ohne Rest teilbar] ==> a - b = k dot n \ ==> b - a = - k dot n ==> (b, a) in R_n ==> b tilde a space checkmark$
], [
transitiv: zz: $a tilde b and b tilde c ==> a tilde c$
$
a tilde b ==> a - b = k dot n \
b tilde c ==> b - c = l dot n
$
Gleichungen addieren: $a - c = n(k + l) ==> a tilde c space checkmark$
])
Für $a$ wird die Äquivalenzklasse $[a]$ auch die Restklasse von $a #italic[modulo] n$ genannt.
$
[a] = a + n dot z := {a + n z | z in ZZ}
$
Die Äquivalenzrelation $R_n$ definiert auch eine Zerlegung der Menge $ZZ$ in disjunkte Teilmengen, nämlich
$
[0] union [1] union ... union [n-1] = union.big_(a = 0)^(n-1) [a] = ZZ
$
Es gilt allgemein: Ist $tilde$ eine Äquivalenzrelation auf $M$, so ist $M$ die Vereinigung aller Äquivalenzklassen.
#boxedlist([
"$subset.eq$": $#sspace$
#v(-2mm)
$
M = union.big_(a in M) {a} subset.eq union.big_(a in M) [a] space checkmark
$
], [
"$supset.eq$":
#v(-2mm)
$
[a] subset M ==> union.big_(a in M) [a] subset.eq M space checkmark
$
])
#endproof
#bold[Satz 1.22:] Ist $R$ eine Äquivalenzrelation auf der Menge $M$ und sind $a, b in M$, dann sind folgende Aussagen äquivalent:
#align(center, grid(columns: (auto, auto, auto), gutter: 2cm, [1) $[a] = [b]$], [2) $[a] sect [b] != emptyset$], [3) $a tilde b$]))
#italic[Beweis:] Durch Ringschluss
zu zeigen: $1 ==> 2, 2 ==> 3, 3 ==> 1$
$1 ==> 2$:
#align(center, box(width: 90%, [Wegen $a tilde a ==> a in [a] = [b] ==> a in [a] sect [b] ==> [a] sect [b] != emptyset$]))
$2 ==> 3$:
#align(center, box(width: 90%, [Aus $[a] sect [b] != emptyset ==>$ es existiert $c in [a] sect [b]$. Nach Definition gilt dann $c tilde a$ wegen der Symmetrie von $a tilde c$. Nach Definition auch $c tilde b$. Wegen der Transitivät der Relation gilt dann auch $a tilde b$]))
$3 ==> 1$:
#align(center, box(width: 90%, [Es gilt $a tilde b$. Sei $c in [a] ==> c tilde a$. Wegen der Transitivät folgt \ $c tilde b ==> c in [b] ==> [a] subset.eq [b]$. Analog folgt $[b] subset.eq [a]$.]))
#endproof
Aus Satz 1.22 2) folgt, dass die Äquivalenzklassen eine disjunkte Zerlegung der Menge $M$ darstellen.
#definition("1.23", "maximales Element, obere Schranke")[Sei $M$ eine Menge und sei für jedes Element $m in M$ eine weitere Menge $S_m$ gegeben. Für $cal(S) := {S_m | m in M}$ ist die Teilmengenrelation $subset.eq$ eine partielle Ordnung. Die Menge $cal(S)$ heißt dann #bold[partiell geordnet]. Eine Menge $hat(S) in cal(S)$ heißt #bold[maximales Element] von $cal(S)$ (bezüglich $subset.eq$), wenn aus $S in cal(S)$ und $hat(S) subset.eq S$ folgt, dass $S = hat(S)$ ist. Eine nichtleere Teilmenge $cal(K) subset.eq cal(S)$ heißt #bold[Kette] (bezüglich $subset.eq$), wenn für alle $K_1, K_2 in cal(K)$ gilt, dass $K_1 subset.eq K_2$ oder $K_2 subset.eq K_1$. Ein Element $hat(K) in cal(S)$ heißt #bold[obere Schranke] der Kette $cal(K)$, wenn $K subset.eq hat(K)$ für alle $K in cal(K)$ gilt.] <def>
#bold[Beispiel 1.24:] Sei $cal(S) = P({2, 4, 6, 8, 10})$
Dann ist $cal(K) = {emptyset, {2}, {2, 6}, {2, 6, 10}} subset.eq cal(S)$ eine Kette.\
Die Menge $K = {2, 6, 10}$ ist die obere Schranke von $cal(K)$,\
das maximale Element von $cal(S)$ ist $hat(S) = {2, 4, 6, 8, 10}$.
#bold[Lemma 1.25: Zornsche Lemma]
Sei $M$ eine Menge und sei $cal(S) subset.eq cal(P)(M)$ eine nichtleere Menge mit der Eigenschaft, dass für jede Kette $cal(K) subset.eq cal(S)$ auch ihre Vereinigunsmenge in $cal(S)$ liegt, d.h.
$
union.big_(A in cal(K)) A in cal(S)
$
Dann besitzt $cal(S)$ ein maximales Element.
#italic[Beweis:] Das Zornsche Lemma ist ein fundamentales Resultat aus der Mengenlehre, hier ohne Beweis
#endproof
#bold[Lemma 1.26:] Sei $M$ eine Menge und $cal(K) subset.eq cal(P)(M)$ eine Kette. Dann gibt es zu je endlich vielen $A_1, ..., A_n in cal(K)$ ein $hat(dotless.i) in {1, ..., n}$ mit $A_i subset.eq A_(hat(dotless.i))$ für alle $i in {1, ..., n}$.
#italic[Beweis:] Durch vollständige Induktion über $n$.
Induktionsanfang: n = 1
D.h. wir haben $A_1 in cal(K)$ und für $hat(dotless.i) = 1$ gilt $A_1 subset.eq A_(hat(dotless.i)) = A_1 space checkmark$
Induktionsschritt: $n - 1 arrow.bar n$
Für $A_1, ..., A_(n-1) in cal(K)$ exisitert ein $hat(dotless.j) in {1, ..., n-1}$ mit $A_i subset.eq A_(hat(dotless.j))$ für alle $i in {1, ..., n-1}$. Mit
$
hat(dotless.i) := cases(hat(dotless.j) "für" A_n subset.eq A_(hat(dotless.j)), n "für" A_(hat(dotless.j)) subset.eq A_n)
$
folgt die Behautpung.
#endproof
== Abbildungen
#definition("1.27", "Abbildungen")[Es Seien $X$ und $Y$ beliebig, nichtleere Mengen. Eine #bold[Abbildung] von $X$ nach $Y$ ist eine Vorschrift $f$, die jedem Element $x in X$ genau ein Element $f(x) in Y$ zuordnet. Man schreibt
$
f: X arrow Y, space x arrow.bar y = f(x)
$
Die Menge $X$ heißt #bold[Definitionsbereich] von $f$, die Menge $Y$ heißt #bold[Wertebereich] von $f$
#underline[Achtung:] Jede Abbildung besteht aus drei "Teilen". Angabe des Definitionsbereichs, Angabe des Wertebereichs, Angabe der Zuordnungsvorschrift.] <def>
#bold[Beispiel 1.28:] Sei $M$ eine nichtleere Menge. Dann ist
$
f: M arrow N, space x arrow.bar x = f(x)
$
eine Abbildung $f$ #bold[Identität] von $M$ mit der Notation $I_m \/ "Id"_m$.
Sei $X = Y = RR$, dann ist $f: RR arrow RR, space x arrow.bar f(x) := 7x + 2$ eine Abbildung.
#definition("1.29", "Bild, Urbild")[Seien $X, Y$ beliebige nichtleere Mengen und $f: X arrow Y$. Es gelte $M subset.eq X$ und $N subset.eq Y$. Dann heißen die Mengen:
$
f(M) &:= {f(x) in Y | x in M} subset.eq Y #[das #bold[Bild] von $M$ unter $f$.] \
f^(-1)(N) &:= {x in X | f(x) in N} subset.eq X #[das #bold[Urbild] von $N$ under $f$.]
$
Ist $emptyset != M subset.eq X$, dann heißt $f_(|M): M arrow Y, space x arrow.bar f(x)$, die #bold[Einschränkung] von $f$ auf $M$.
] <def>
#bold[Beispiel 1.30:] Sei $X = Y = RR$ und $x arrow.bar f(x) = x^4$. Dann ist $RR$ Definitions- und Wertebereich von $f$.
#boxedlist([$f(RR) = RR_+ := [0, infinity[$ das Bild von $f$ #v(2mm)], [$f([0,2]) = [0, 16]$ #v(2mm)], [$f^(-1)([16, 81]) = [-3, -2] union [2, 3]$ das Urbild des Intervalls $[16, 81]$ unter $f$. #v(2mm)])
#definition("1.31", "injektiv, surjektiv, bijektiv")[Seien $X, Y$ zwei beliebige, nichtleere Mengen und $f : X arrow Y$ eine Abbildung. Dann heißt $f$:
#boxedlist([#bold[injektiv:] falls für alle $x, tilde(x) in X$ gilt: $#sspace$
#v(-1mm)
$
f(x) = f(tilde(x)) ==> x = tilde(x)
$
#v(1mm)
],[
#bold[surjektiv:] falls für jedes $y in Y$ gilt:
#v(-1mm)
$
exists space.sixth x in X: f(x) = y
$
#v(1mm)
],[
#bold[bijektiv:] falls $f$ injektiv und surjektiv ist
])] <def>
Man kann sich anhand der Definition leicht überlegen, dass eine Abbildung $f: X arrow Y$ genau dann bijektiv ist, wenn es für jedes $y in Y$ #underline[genau] ein $x in X$ gibt, sodass $f(x) = y$ gilt.
#bold[Beispiel 1.32:] Betrachte die Funktion $f: RR arrow RR, space x arrow.bar max(0, x)$
#boxedlist[$f: RR arrow RR$, $f$ ist weder injektiv noch surjektiv][$f: RR arrow RR_+$, $f$ ist surjektiv, aber nicht injektiv][$f: RR_+ arrow RR$, $f$ ist injektiv aber nicht surjektiv][$f: RR_+ arrow RR_+$, $f$ ist bijektiv]
#definition("1.33", "Komposition")[Seien $X, Y, Z$ nichtleere Mengen und die Abbildungen $f: X arrow Y, space x arrow.bar f(x)$ sowie $g: Y arrow Z, space y arrow.bar g(y)$ gegeben. Dann ist die #bold[Komposition] oder #bold[Hintereinanderausführung] von $f$ und $g$ die Abbildung
$
g compose f: X arrow Z, space x arrow.bar g(f(x)) in Z
$
] <def>
#bold[Satz 1.34:] Seien $W, X, Y$ und $Z$ nichtleere Mengen, und die Abbildungen $f: W arrow X$, $g: X arrow Y$, $h: Y arrow Z$ gegeben. Dann gilt:
#box(width: 100%, inset: (right: 1cm, left: 1cm), [
1. $h compose (g compose f) = (h compose g) compose f$, d.h. die Komposition von Abbildungen ist Assoziativ
2. Sind beide Abbildungen $f$ und $g$ injektiv/surjektiv/bijektiv, dann ist auch die Komposition $g compose f$ injektiv / surjektiv / bijektiv.
3. Ist $g compose f$ injektiv, dann ist $f$ injektiv
4. Ist $g compose f$ surjktiv, dann ist $g$ surjektiv
])
#italic[Beweis:] (Übungsaufgabe, Blatt 4 Aufgabe 1)
1. $h compose (g compose f)(x) = h((g compose f)(x)) = h(g(f(x))) = (h compose g)(f(x)) = ((h compose g) compose f)(x)$
2. #[Für jedes $x_1, x_2 in X$ folgt aus $g$ injektiv: $g(f(x_1)) = g(f(x_2)) ==> f(x_1) = f(x_2)$. Aus $f$ injektiv folgt wiederum: $f(x_1) = f(x_2) ==> x_1 = x_2$. Also gilt $g(f(x_1)) = g(f(x_2)) ==>$ $x_1 = x_2$. Somit ist $g compose f$ injektiv.
Für jedes $z in Z$ folgt aus $g$ surjektiv: $exists space.sixth y in Y: f(y) = z$. Für jedes $y in Y$ folgt aus $f$ surjektiv wiederum: $exists space.sixth x in X: f(x) = y$. Also folgt $forall space.sixth z in Z space.sixth exists space.sixth x in X: g(f(x)) = z$. Somit ist $g compose f$ surjektiv.
Sind $f$ und $g$ bijektiv, folgt aus den obigen Beweisen, dass $g compose f$ injektiv und surjektiv ist. Somit ist $g compose f$ auch bijektiv.
]
3. Ist $f$ nicht injektiv, dann existieren $x_1, x_2 in X$ mit $f(x_1) = f(x_2)$ aber $x_1 != x_2$. Wegen $g compose f$ injektiv gilt $g(f(x_1)) = g(f(x_2)) ==> x_1 = x_2$. Damit $g(f(x_1)) = g(f(x_2))$ gilt, muss auch $f(x_1) = f(x_2)$ gelten, dann gilt aber auch $f(x_1) = f(x_2) ==> x_1 = x_2$. Dies ist ein Widerspruch $arrow.zigzag$. $f$ ist also injektiv.
4. Ist $g$ nicht surjektiv, dann existiert ein $z in Z$ für das kein $y in Y$ mit $g(y) = z$ existiert. Wegen $g compose f$ surjektiv gilt $forall space.sixth z in Z space.sixth exists space.sixth x in X: g(f(x)) = z$. Dann gilt auch $g(f(x)) = g(y) = z, space y in Y$, also existiert ein $y in Y$ mit $g(y) = z$. Dies ist ein Widerspruch $arrow.zigzag$. Also ist $g$ surjektiv.
#endproof
#bold[Satz 1.35:] Seien $X, Y$ nichtleere Mengen und $f: X arrow Y$ eine Abbildung. Die Abbildung ist genau dann bijektiv, wenn es eine Abbildung $g: Y arrow X$ existiert, so dass $g compose f = "Id"_X$ und $f compose g = "Id"_Y$ gilt.
#italic[Beweis:]
"$==>$"
Zu jedem $y in Y$ existiert genau ein $x_y in X$ mit $f(x_y) = y$. Damit kann man eine Abbildung $g$ definieren durch:
$
g: Y arrow X, space g(y) = x_y
$
Für $y in Y$ folgt dann $(f compose g)(y) = f(g(y)) = f(x_y) = y ==> f compose g = "Id"_Y$.
Sei $x in X ==>$ $f(x) = y in Y$. Wegen der Bijektivität von $f$ folgt $x = x_y in X$
Dann gilt:
$
(g compose f)(x) = g(f(x)) = g(y) = x_y = x ==> g compose f = "Id"_X
$
"$<==$":
Es gilt: $g compose f = "Id"_X$, $"Id"_X$ ist injektiv. Wegen Satz 1.34, 3) ist dann auch $f$ injektiv. Des weiteren gilt $f compose g = "Id"_Y$ ist surjektiv. Wegen 1.34, 4) ist dann auch $f$ surjektiv $==>$ $f$ ist bijektiv
#bold[Frage:] Gibt es eine weitere Abbildung, $tilde(g): Y arrow X$ mit den gleichen Eigenschaften wie im letzten Satz? Wegen Satz 1.34, 1) gilt:
$
tilde(g) = "Id"_X compose tilde(g) = (g compose f) compose tilde(g) = g compose (f compose tilde(g)) = g compose "Id"_Y = g
$
#definition("1.36", "inverse Abbildung / Umkehrabbildung")[
Seien $X, Y$ zwei nichtleere Mengen und $f: X arrow Y$ eine Abbildung. Ist $f$ bijektiv, dann heißt die in Satz 1.35 definierte, eindeutige Abbildung $g: Y arrow X$ #bold[inverse Abbildung] oder #bold[Umkehrabbildung] von $f$ und wird $f^(-1)$ bezeichnet.
] <def>
#bold[Beispiel 1.37:] Die Abbildung $f: RR arrow RR, space f(x) = 3x - 5$ ist bijektiv. Die zu $f$ inverse Abbildung erhält man durch Umformung.
$
y = 3x - 5 <==> y + 5 = 3x <==> x = 1/3(y+5)
$
Also $f^(-1): RR arrow RR, space y arrow.bar 1/3(y+5)$
#bold[Achtung:] $f: RR arrow RR, f(x) = x^2$ ist nicht bijektiv.
$
tilde(f): RR arrow RR_+, space tilde(f)(x) = x^2 wide wide tilde(f)^(-1)(y) = sqrt(y)
$
#bold[Achtung:] Die Notation $f^(-1)$ ist doppelt Belegt! Zum einen für die Notation der Umkehrabbildung und zum Anderen für die Notation des Urbilds.
#bold[Satz 1.38:] Seien $X, Y$ und $Z$ nichtleere Mengen und die Abbildungen $f: X arrow Y$ sowie $g: Y arrow Z$ bijektiv.
Dann gilt:
#box(width:100%, inset: (left: 1cm, right: 1cm), [
1. $f^(-1)$ ist bijektiv $wide (f^(-1))^(-1) = f$ #v(1mm)
2. $(g compose f)^(-1) = f^(-1) compose g^(-1)$
])
#italic[Beweis:] (1. Übungsaufgabe)
1. #[
$
f &= f compose "Id"_X \ &= f compose (f^(-1) compose (f^(-1))^(-1)) \ &= (f compose f^(-1)) compose (f^(-1))^(-1) \ &= "Id"_Y compose (f^(-1))^(-1) \ &= (f^(-1))^(-1)
$
]
2. #[Aus Satz 1.34 folgt, dass $g compose f$ bijektiv ist. $==>$ $(g compose f)^(-1)$ existiert und ist eindeutig bestimmt. Es gilt
$
(f^(-1) compose g^(-1)) compose (g compose f) \
&= f^(-1) compose ((g^(-1) compose g) compose f) \
&= f^(-1) compose ("Id"_Y compose f) \
&= f^(-1) compose f = "Id"_X
$
Analog zeigt man: $(g compose f) compose (f^(-1) compose g^(-1)) = "Id"_Y$
$
==> (g compose f)^(-1) = f^(-1) compose g^(-1)
$
]
#endproof
#pagebreak()
= Algebraische Strukturen
Algebraische Strukturen sind Mengen und Verknüpfungen, die auf den Elementen der Menge definiert sind. Ein Beispiel dafür ist die Menge aller ganzen Zahlen mit der Addition als Verknüpfung.
Algebraische Strukturen besitzen wichtige Eigenschaften:
#boxedlist[Die Summe zweier ganzer Zahlen ist wieder eine ganze Zahl $corres$ Abgeschlossenheit der Menge bezüglich der Verknüpfung][Es gibt die ganze Zahl 0, sodass für jede ganze Zahl $a in ZZ$ gilt: $0 + a = a$. Dieses Element nennt man das neutrale Element][Für jede ganze Zahl $a in Z$ gibt es ein $-a in ZZ$, sodass gilt: $(-a) + a = 0$. Dieses Element nennt man das inverse Element von $a$]
Algebraische Strukturen erlauben es uns, abstrakte Konzepte aus konkreten Beispielen zu extrahieren und später komplexe Zusammenhänge mit diesen Konzepten zu analysieren und Stück für Stück zu erweitern.
== Gruppen
#definition("2.1", "innere Verknüpfung, Halbgruppe")[Sei $M$ eine nichtleere Menge. Eine Abbildung $circ: M times M arrow M, space (a, b) arrow.bar a circ b$ heißt #bold[(innere) Verknüpfung] auf $M$. Gilt: $(a circ b) circ c = a circ (b circ c)$, dann heißt die Verknüpfung #bold[assoziativ] und $(M, circ)$ eine #bold[Halbgruppe]. Gilt für eine Halbgruppe, dass $a circ b = b circ a$, so heißt die Halbgruppe #bold[abelsch] oder #bold[kommutativ].] <def>
Je nach Kontext kann die Notation einer Verknüpfung variieren. ($a circ b$, $a dot b$, $a b$)
#bold[Beispiel 2.2:]
#boxedlist[$(NN, +)$ und $(NN, ast)$ sind kommutative Halbgruppen][Sei $X$ eine nichtleere Menge. Dann ist $M := "Abb"(X, X)$ $= {"Abbildungen" f: X arrow X}$ eine Halbgruppe mit der Verknüpfung $compose$ als Komposition von Abbildungen (Def. 1.33). Diese Halbgruppe ist nicht abelsch.
Beweis durch Gegenbeispiel:
Sei $a, b, c in X, a != b, a != c, b != c$. Definiere $f, g in M$ mit
]
$
f(x) := cases(b "für" x = a, a "für" x = b, x "sonst") wide wide g(x) := cases(c "für" x = a, a "für" x = c, x "sonst")
$
#h(1cm) Dann folgt:
$
(f compose g)(a) = f(g(a)) = f(c) = c \
(g compose f)(a) = g(f(a)) = g(b) = b \
checkmark
$
Die Halbgruppe ist ein relativ "schwaches" Konzept. Deswegen braucht man weitere Eigenschaften:
#definition("2.3", "neutrales Element")[
Sei $M$ eine nichtleere Menge und $circ$ eine innere Verknüpfung auf $M$. Existiert ein Element $e in M$ mit
$
a circ e = e circ a = a wide forall space.sixth a in M
$
so heißt $e$ #bold[neutrales Element] für die Verknüpfung $circ$.
Eine Halbgruppe, die ein neutrales Element besitzt heißt #bold[Monoid].
] <def>
#bold[Beispiel 2.4:] Kein Monoid
Gegeben sei die Menge $M = {a, b}$ und die folgende Verknüfung
#align(center, tablex(
columns: 3,
auto-lines: false,
(), vlinex(), (), (),
$circ$, $a$, $b$,
hlinex(),
$a$, $a$, $b$,
$b$, $a$, $b$,
))
Man kann nachrechenen, dass $(M, circ)$ eine Halbgruppe ist. Man kann auch prüfen, dass $a$ linksneutral aber nicht rechtsneutral ist, sowie dass $b$ rechtsneutral aber nicht linksneutral ist. Somit besitzt die Halbgruppe kein neutrales Element, $(M, circ)$ ist also kein Monoid.
#bold[Bemerkung:] In der Definition eines Monoids wird nur die Existenz aber nicht die Eindeutigkeit des neutralen Elements gefordert. Ist dies sinnvoll?
#bold[Lemma 2.5:] Sei $(M, circ)$ ein Monoid und $e_1, e_2 in M$ neutrale Elemente, dann gilt
$
e_1 = e_2
$
#italic[Beweis:]
$
e_1 &= e_1 circ e_2 \
&= e_2
$
#endproof
#bold[Beispiel 2.6:]
#boxedlist[$(NN, +)$ ist kein Monoid, da kein neutrales Element existiert ($0 in.not NN$ in LinA)][$(NN, dot)$ ist ein Monoid mit dem neutralen Element $e = 1$][Für $NN_0 = NN union {0}$ ist $(NN_0, +)$ ein Monoid mit dem neutralen Element $e = 0$]
#definition("2.7", "Gruppen")[Ein Monoid $(M, circ)$ ist eine #bold[Gruppe], wenn für jedes $a in M$ ein $b in M$ existiert, so dass
$
a circ b = b circ a = e
$
wobei $e$ das neutrale Element des Monoids ist. Wir nennen $b$ das #bold[inverse Element] zu dem gegebenen Element $a$ und bezeichnen es mit $a^(-1) = b$.
] <def>
#bold[Bemerkung:] Für $circ = +$, d.h. additiv geschriebene Gruppen schreibt man auch $-a := b$.
#bold[Beispiel 2.8:]
#boxedlist[$(ZZ, +)$, $(QQ, +)$ und $(RR, +)$ sind kommutative Gruppen][$(NN, +)$ ist keine Gruppe, da kein neutrales Element und keine inversen Elemente existieren][Rechnen mit binären Zahlen
Betrachtet wird $FF_2 = {0, 1}$ und die Verknüpfungen
#set align(center)
#box(width: 50%, grid(columns: (1fr, 1fr),
tablex(
columns: 3,
auto-lines: false,
align: horizon + center,
(), vlinex(), (), (),
$+$, $0$, $1$,
hlinex(),
$0$, $0$, $1$,
$1$, $1$, $0$,
),
tablex(
columns: 3,
auto-lines: false,
align: horizon + center,
(), vlinex(), (), (),
$dot$, $0$, $1$,
hlinex(),
$0$, $0$, $0$,
$1$, $0$, $1$,
),
))
#set align(left)
Anhand der Verknüpfungstabellen erkennt man, dass $(FF_2, +)$ mit dem neutralen Element $e = 0$ eine abelsche Gruppe ist. Jedoch ist $(FF_2, dot)$ keine Gruppe, da zwar ein neutrales Element $e = 1$, aber das Element $0$ kein inverses Element besitzt.
]
#bold[Satz 2.9:] Sei $(M, circ)$ eine Gruppe, dann gilt:
#box(width: 100%, inset: (left: 1cm, right: 1cm), [
1. Es gibt #bold[genau ein] neutrales Element in $M$.
2. Jedes Element der Menge $M$ besitzt #bold[genau ein] inverses Element.
3. Jedes linksinverse Element ist gleichzeitig auch rechtsinvers.
4. Jedes linksneutrale Element ist gleichzeitig auch rechtsneutral.
]
)
#italic[Beweis:]
1. Folgt aus Lemma 2.5, da $(M, circ)$ nach Definition ein Monoid ist.
2. #[
Annahme: Seien $b in M$ und $tilde(b) in M$ inverse Elemente zu $a in M$.
zu zeigen: $b = tilde(b)$
Dann gilt:
$
b &= b circ e \
&= b circ (a circ tilde(b)) \
&= (b circ a) circ tilde(b) \
&= e circ tilde(b) \
&= tilde(b)
$
]
3. #[
Es sei $b in M$ ein linksinverses Element zu $a in M$. D.h. $b circ a = e$. Sei $tilde(b) in M$ ein linksinverses Element zu $b in M$. D.h. $tilde(b) circ b = e$.
$
a circ b &= e circ (a circ b) \
&= tilde(b) circ b circ (a circ b) \
&= tilde(b) circ (b circ a) circ b \
&= tilde(b) circ e circ b \
&= tilde(b) circ b \
&= e #hide($tilde(b)$)
$
]
4. #[
Es gelte $e circ a = a$ und $b circ a = a circ b = e$
Dann gilt: $a circ e = a circ (b circ a) = (a circ b) circ a = a wide checkmark$
]
#bold[Lemma 2.10:] Sei $(M, circ)$ eine Gruppe. Gilt für ein $a in M$, dass $c circ a = a$ für ein $c in M$; dann ist $c$ das neutrale Element der Gruppe.
#italic[Beweis:] Sei $e$ das neutrale Element (es gibt genau 1) der Gruppe $(M, circ)$ und für $a, c in M$ gelte: $c circ a = a$. Sei $b$ das inverse Element zu $a$.
$
c &= c circ e \
&= c circ (a circ b) \
&= (c circ a) circ b \
&= a circ b \
&= e
$
#endproof
Besonders wichtig in der linearen Algebra sind Abbildungen zwischen Gruppen, die bezüglich der Verknüpfung "kompatibel" sind.
#definition("2.11", "Homomorphismus")[
Seien $(M, circ)$ und $(N, oplus)$ Gruppen. Eine Abbildung $f: M arrow N$ heißt #bold[Homomorphismus] (oder #bold[Gruppenhomomorphismus]) falls:
$
f(x circ y) = f(x) oplus f(y) wide forall space.sixth x, y in M
$
Ein Homomorphismus heißt #bold[Isomorphismus], wenn er bijektiv ist.
] <def>
#bold[Beispiel 2.12:] Die Abbildung $f: RR arrow RR_(>0)$ mit $f(x) = e^(2x)$ ist ein Homomorphismus zwischen $(RR, +)$ und $(RR_(>0), dot)$ mit $RR_(>0) = {x in RR | x > 0}$ denn
$
f(x + y) = e^(2(x+y)) = e^(2x) dot e^(2y) = f(x) dot f(y)
$
#bold[Satz 2.13:] Sei $f: M arrow N$ für die Gruppen $(M, circ)$ und $(N, oplus)$ ein Homomorphismus sowie $e_M$ und $e_N$ jeweils die neutralen Elemente. Dann gilt $f(e_M) = e_N$.
#italic[Beweis:] Sei $a in M$ beliebig gewählt, dann folgt
$
f(a) = f(e_M circ a) = f(e_M) oplus f(a) = e_N oplus f(a) \
attach(==>, t: "2.10") f(e_M) "ist ein neutrales Element" attach(==>, t: "2.9") f(e_M) = e_N
$
#endproof
Homomorphismen bilden das neutrale Element im Definitionsbereich immer auf das neutrale Element des Wertebereichs ab. Später werden wir sehen, dass wenn der Homomorphismus nicht bijektiv ist, noch mehr Elemente auf das neutrale Element im Wertebereich $e_N$ abgebildet werden können. Dies motiviert folgende Definition:
#definition("2.14", "Kern")[
Ist $f: (M, circ) arrow (N, oplus)$ ein Homomorphismus, so nennt man: $#sspace$
$
ker(f) := {a in M | f(a) = e_N}
$
den #bold[Kern] von $f$.
] <def>
== Ringe
Ringe sind eine Erweiterung der algebraischen Strukturen von einer auf zwei Verknüpfungen.
#definition("2.15", "Ring")[
Seien $R$ eine Menge und "$+$" sowie "$dot$" zwei Verknüpfungen auf $R$. Das Tripel $(R, +, dot)$ heißt #bold[Ring], falls gilt:
#box(width: 100%, inset: (left: 0.5cm, right: 0.5cm), [
1. $(R, +)$ ist eine kommutative Gruppe, deren neutrales Element wir mit $0$ bezeichnen.
2. $(R, dot)$ ist eine Halbgruppe, d.h. es gilt das Assoziativgesetz.
3. #[
Es gelten die Distributivgesetze: $forall a, b, c in R$
$
a dot (b + c) = a dot b + a dot c \
(a + b) dot c = a dot c + b dot c
$
]
Ein Ring heißt kommutativ, wenn $dot$ kommutativ ist. D.h. $a dot b = b dot a, space forall space.sixth a, b in R$. Ein Element $1 in R$ heißt #bold[Einselement], wenn es das neutrale Element bezüglich der Multiplikation ist. Das heißt wenn für alle $a in R$ gilt: $1 dot a = a dot 1 = a$.
])
] <def>
#bold[Achtung:] Die Formulierung der Distributivitätsgesetze impliziert, dass die Multiplikation stärker bindet als die Addition ("Punkt vor Strich").
#bold[Beispiel 2.16:]
#boxedlist[$(NN, +, dot)$ ist kein Ring][$(ZZ, +, dot)$ ist ein kommutativer Ring mit Einselement]
#boxedlist[
$(FF_2, +, dot)$ ist ein kommutativer Ring mit Einselement, denn
#boxedlist[das neutrale Element bezüglich der Addition ist die $0$, denn $0 + 0 = 0$, $0 + 1 = 1$, $1 + 0 = 1$][das additive inverse Element zu $0$ ist $0$ und zu $1$ die $1$, denn $1 + 1 = 0$][die Addition ist kommutativ][die Addition ist assoziativ, zeigt man durch nachrechnen für alle $8$ Möglichkeiten][das neutrale Element für die Multiplikation ist $1$, denn $0 dot 1 = 0$ und $1 dot 1 = 1$][die Multiplikation ist kommutativ][die Multiplikation ist assoziativ, zeigt man durch nachrechnen][die Distributivgesetze gelten, zeigt man durch nachrechnen]
]
In Ringen gelten die "üblichen" Rechenregeln, z.B.:
$
0 dot a = 0
$
#italic[Beweis:]
$
0 dot a &= 0 dot a + 0 dot a - 0 dot a = (0 + 0) dot a - 0 dot a \
&= 0 dot a - 0 dot a = 0
$
oder auch
$
(-1) dot a = -a
$
#italic[Beweis:]
$
a + (-1) dot a &= 0, "denn" \
a + (-1) dot a &= 1 dot a + (-1) dot a = (1 + (-1)) dot a = 0 dot a = 0
$
analog zeigt man $a dot 0 = 0$ und $a dot (-1) = -a$
#bold[Bemerkung:] Wenn in einem Ring die Gleichung $1 = 0$ gilt, folgt
$
a = a dot 1 = a dot 0 = 0
$
Somit muss $R$ der Nullring sein, $R = {0}$.
#bold[Beispiel 2.17:] Ring der Polynome
Sei $(R, +, dot)$ ein kommutativer Ring mit Eins. Ein Polynom mit Koeffizienten in $R$ und der Unbekannten $t in R$ (kurz Polynom über $R$) ist gegeben durch
$
p(t) = a_0 dot t^0 + a_1 dot t^1 + ... + a_n dot t^n, wide a_0, a_1, ..., a_n in R
$
Die Menge aller Polynome über $R$ wird mit $P[t]$ bezeichnet.
Betrachte zwei Polynome $p, q in P[t]$ mit
$
p(t) = a_0 + a_1 t + ... + a_n t^n "und" q(t) = b_0 + b_1 t + b_m t^m
$
mit $n >= m$. Ist $n > m$, so setzen wir $b_j = 0$ für $j = m + 1, ..., n$. $p(t)$ und $q(t)$ sind gleich, wenn $a_j = b_j$ für alle $j in {1, ..., n}$ gilt.
Aufgrund der Eigenschaften von $R$ gilt
$
a_0 + a_1 t + ... + a_(n-1) t^(n-1) + a_n t^n = a_n t^n + a_(n-1) t^(n-1) + ... + a_1 t + a_0
$
Der Grad eines Polynoms $p(t) in P[t]$ ist definiert als der größte Index $j$ für den $a_j != 0$ gilt. Gibt es keinen solchen Index, ist $p(t)$ das Nullpolynom, d.h. $p(t) = 0$ für alle $t in R$ und man definiert den Grad von $p(t)$ als $- infinity$.
Sind zwei Polynome $p, q in P[t]$ wie oben definiert, und setzen wir wieder $b_j = 0$ für alle $j in {m+1, ..., n}$, dann sind die Verknüpfungen "$+$" und "$dot$" wie folgt definiert:
$
p(t) + q(t) = (a_0 + b_0) + (a_1 + b_1) t + ... +(a_n + b_n) t^n "und" \
p(t) dot q(t) = c_0 + c_1 t + ... + c_(n+m) t^(n+m), wide c_k := sum_(i+k = k) a_i dot b_j
$
Mit dem Nullpolynom definiert wie oben und dem Einspolynom definiert als $p(t) := 1$ kann man nachrechnen, dass $(P[t], +, dot)$ ein kommutativer Ring ist.
#definition("2.18", "invertierbar")[
Es sei $(R, +, dot)$ ein Ring mit Eins und $a in R$ gegeben. Ein Element $b in R$ heißt #bold[invers] (bezüglich $dot$) zu $a$, wenn gilt:
$
a dot b = b dot a = 1
$
Existiert zu $a in R$ ein inverses Element, so heißt $a$ #bold[invertierbar].
] <def>
#bold[Satz 2.19:] Es sei $(R, +, dot)$ ein Ring mit Eins. Dann gilt:
#box(width: 100%, inset: (right: 1cm, left: 1cm), [
1. Existiert zu $a in R$ ein inverses Element bezüglich $dot$, so ist dies eindeutig bestimmt. Dies wird mit $a^(-1)$ gekennzeichnet.
2. Wenn $a, b in R$ invertierbar sind, dann ist auch $a dot b$ invertierbar und es gilt:
$
(a dot b)^(-1) = b^(-1) dot a^(-1)
$
])
#italic[Beweis:] Siehe oben im Abschnitt zu Abbildungen.
#endproof
== Körper
Eine knappe Definition eines Körpers:
Ein kommutativer Ring mit Eins heißt Körper, falls $0 != 1$ gilt (der Nullring wird ausgeschlossen) und jedes Element $a in R backslash {0}$ invertierbar ist.
Es folgt eine äquivalente und formalere Definition:
#definition("2.20", "Körper")[
Eine Menge $K$ mit zwei Verknüpfungen
$
+: K times K arrow K, space (a, b) arrow.bar a + b wide wide "Addition" \
dot: K times K arrow K, space (a, b) arrow.bar a dot b wide space "Multiplikation"
$
heißt #bold[Körper], wenn gilt:
#boxedlist[$(K, +)$ ist eine kommutative Gruppe #sspace][$(K backslash {0}, dot)$ ist auch eine kommutative Gruppe][
Es gelten die Distributivgesetze
$
a dot (b + c) = a dot b + a dot c \
(a + b) dot c = a dot c + b dot c
$
]
] <def>
#bold[Lemma 2.21:] Sei $(K, +, dot)$ ein Körper. Gilt für $a, b in K$, dass $a dot b = 0$, so ist mindestens eins davon die $0$.
#italic[Beweis:]
Fall 1: $a = b = 0$
Fall 2: o.B.d.A: $a != 0 ==> exists space.sixth a^(-1): a dot a^(-1) = 1$
$
b = 1 dot b = (a^(-1) dot a) dot b = a^(-1) dot (a dot b) = a^(-1) dot 0 = 0
$
#endproof
Diese Eigenschaft nennt man Nullteilerfreiheit.
#bold[Beispiel 2.22:]
#boxedlist[$(RR, +, dot)$ ist ein Körper][$(ZZ, +, dot)$ ist kein Körper, da die multiplikativ inversen Elemente in $QQ$, aber nicht immer in $ZZ$ liegen]
#bold[Beispiel 2.23:] komplexe Zahlen
Die Menge der komplexen Zahlen ist definiert als:
$
CC := {(x, y) | x, y in RR}
$
d.h. $CC = RR times RR$. Die zwei Verknüpfungen Addition und Multiplikation werden wie folgt definiert:
$
+ &: CC times CC arrow CC, space (a, b) + (c, d) = (a + c, b + d) \
dot &: CC times CC arrow CC, space (a, b) dot (c, d) = (a dot c - b dot d, a dot d + b dot c)
$
Wir verwenden implizit die Operationen auf den reellen Zahlen, $+, -, dot$. Dann sieht man:
#boxedlist[Das neutrale Element in $CC$ bezüglich $+$ ist die $0_CC = (0,0)$][Das neutrale Element in $CC$ bezüglich $dot$ ist die $1_CC = (1, 0)$]
Man rechnet nach, dass
#boxedlist[
Das inverse Element bezüglich $+$ in $CC$ definiert ist mit #sspace
$
-(x, y) = (-x, -y) in CC wide forall space.sixth (x, y) in CC \
$
][
Das inverse Element bezüglich $dot$ in $CC$ definiert ist mit
$
(x, y)^(-1) = (x/(x^2 + y^2), y/(x^2 + y^2)) in CC wide forall space.sixth (x, y) in CC backslash {0_CC}
$
]
Das Überprüfen der Rechengesetze zeigt, dass $CC$ ein Körper ist.
Für die Teilmenge
$
M := {(x, 0) | x in RR} subset CC
$
kann man jedes Element der reellen Zahlen mit einem Element der Menge $M$ mit der bijektiven Abbildung
$
RR arrow M, space x arrow.bar (x, 0)
$
identifizieren. Mit $0_RR arrow.bar (0, 0) = 0_CC$, $1_RR arrow.bar (1, 0) = 1_CC$ kann man $M$ als Teilkörper von $CC$ auffassen. Es gilt jedoch auch $RR subset.eq.not CC$ (zumindest in LinA).
Eine besondere komplexe Zahl ist die imaginäre Einheit $(0, 1)$, für die gilt:
$
(0, 1) dot (0, 1) = (-1, 0) corres -1
$
Dabei wird $(-1, 0) in CC$ mit $-1 in RR$ über die oben genannte bijetkive Abbildung identifiziert. Mit der Definition $i := (0, 1)$ folgt
$
i dot i = -1
$
Mit dieser Notation und Identifikation kann man eine komplexe Zahl $z in CC$ beschreiben mit
$
z = (x, y) &= (x, 0) + (0, y) = (x, 0) + (0, 1) dot (y, 0) \
&= x + i y
$
Man schreibt $"Re"(z) = x$ als #bold[Realanteil] von $z$ und $"Im"(z) = y$ als #bold[Imaginäranteil] von $z$.
Man definiert zu $(x, y) in CC$ die #bold[konjugiert komplexe Zahl] durch
$
overline(z) = (x, -y) in CC
$
Damit erhält man für ein $z = (x, y) in CC$:
$
abs(z) := sqrt(z dot overline(z)) &= sqrt((x + i y) dot (x - i y)) \
&= sqrt(x^2 - i x y + i x y - i^2 y^2) \
&= sqrt(x^2 + y^2)
$
== Vektorräume
#bold[Beispiel 2.24:] Kräfeparallelogramm
Betrachten wir einige Gesetze aus der Mechanik:
Je zwei am selben Punkt angreifende Kräfte können durch eine einzige Kraft ersetzt werden. Diese resultierende Kraft (= Gesamtkraft) hat die gleiche Wirkung wie die Einzelkräfte.
$
F = F_1 + F_2 wide "die Kräfte können als Vektoren betrachtet werden"
$
#boxedlist[Ein Vektor hat eine Länge und eine Richtung][Vektoren kann man addieren][Vektoren können mit einer reellen Zahl multipliziert werden]
#bold[Beispiel 2.25:] Interpolationsproblem
Gegeben sind reelle Zahlen $a, b, c in RR$. Gesucht ist ein Polynom zweiten Grades $p(t) in P[t]$ mit
$
p(1) = a wide p(2) = b wide p(3) = c
$
für ein $p(t) = a_0 + a_1 t + a_2 t^2$. D.h. es muss gelten:
$
p(1) = a_0 + a_1 dot 1 + a_2 dot 1 = a \
p(2) = a_0 + a_1 dot 2 + a_2 dot 4 = b \
p(3) = a_0 + a_1 dot 3 + a_2 dot 9 = c
$
Diese Gleichung hat genau eine Lösung.
$
p(t) = (3a-3b+c) + (-5a/2 + 4b - 3c/2) t + (a/2 - b + c/2) t^2
$
Eine alternative Darstellung ist
$
p_1(t) = 1/2(t - 2)(t - 3) wide p_2(t) = -(t - 1)(t - 3) wide p_3(t) = 1/2(t - 1)(t - 2)
$
für die gilt:
$
p_i(k) = cases(1 "für" i = k, 0 "sonst")
$
Dann ist $p(t)$ gegeben durch:
$
p(t) = a p_1(t) + b p_2(t) + c p_3(t)
$
#bold[Beobachtung:] Die additive Verknüpfung zweier Elemente gleicher Art und Multiplikation mit einer reellen Zahl ($corres$ Skalar).
Solch eine algebraische Sturktur wollen wir beschreiben:
#definition("2.26", "Vektorraum")[
Sei $K$ ein Körper. Ein Vektorraum über $K$, kurz $K$-Vektorraum, ist eine Menge $V$ mit zwei Abbildungen:
#boxedlist[
Addition #sspace
$
+: V times V arrow V, space (v, w) arrow.bar v + w
$
][
skalare Multipliktation
$
dot: K times V arrow V, space (lambda, v) arrow.bar lambda v
$
]
für die folgendes gilt:
#boxedlist[
$(V, +)$ ist eine kommutative Gruppe #sspace
][
Für alle $v, w in V$ und $lambda, mu in K$ gilt:
#box(width: 100%, inset: (left: 4.5cm), [
1. $lambda dot (mu dot v) = (lambda dot mu) dot v$
2. $1 dot v = v$
3. $lambda dot (v + w) = lambda dot v + lambda dot w$
4. $(lambda + mu) dot v = lambda dot v + mu dot v$
])
]
Ein Element $v in V$ nennen wir #bold[Vektor], ein $mu in K$ nenn wir einen #bold[Skalar].
] <def>
#bold[Beobachtung:] Für einen Vektorraum sind die Operatinen $+$ und die skalare Multiplikation $dot$ abeschlossen.
#bold[Beispiel 2.27:] Für einen Körper $K$ ist der Standardvektorraum gegeben durch die Menge $V = K^n$ für ein $n in NN$. Die n-Tupel werden geschrieben als
$
v = vec(v_1, v_2, dots.v, v_n) "mit" v_1, v_2, ..., v_n in K
$
Die Addition und die skalare Multiplikation ist komponentenweise definiert.
$
v + w = vec(v_1, v_2, dots.v, v_n) + vec(w_1, w_2, dots.v, w_n) = vec(v_1 + w_1, v_2 + w_2, dots.v, v_n + w_n) \
lambda dot w = lambda dot vec(w_1, w_2, dots.v, w_n) = vec(lambda dot w_1, lambda dot w_2, dots.v, lambda dot w_n)
$
Damit ist der Vektorraum $V = K^n$ ein $K$-Vektorraum. Der Nullvektor $arrow(v_0)$ ist definiert durch
$
arrow(0) = vec(0, 0, dots.v, 0)
$
Das additiv inverse Element ist gegeben durch
$
-v = - vec(v_1, v_2, dots.v, v_n) = vec(-v_1, -v_2, dots.v, -v_n) "für" v_1, v_2, ..., v_n in K
$
Da $K$ ein Körper ist, ist die so definierte skalare Multiplikation assoziativ, distributiv und mit $1 in K$ kompatibel ($1 dot v = v$).
#bold[Beispiel 2.28:] Polynome
Die Menge $P[t]$ aller Polynome über einen Körper $K$ mit der Unbekannten $t$ bilden einen $K$-Vektorraum, wenn die Addition von Polynomen wie in Beispiel 2.17 definiert ist und die skalare Multiplikation für ein $p(t) = a_0 + a_1 t + ... a_n t^n in P[t]$ definiert ist durch:
$
dot: K times P[t] arrow P[t] \
\
lambda dot p(t) = (lambda a_0) + (lambda a_1) t + ... + (lambda a_n) t^n
$
#bold[Beispiel 2.29:] Abbildungen
Die Menge $V = "Abb"(RR, RR)$ der Abbildungen $f: RR arrow RR$ bilden einen Vektorraum über den Körper $RR$ mit den Verknüpfungen
$
+: V times V arrow V, space (f, g) arrow.bar f + g wide (f + g)(x) := f(x) + g(x)
$
und
$
dot: RR times V arrow V, space (lambda, g) arrow.bar lambda dot g
$
Das Gleiche gilt für
$
V &:= {"stetige Abbildungen" f: RR arrow RR} \
V &:= {"differenzierbare Abbildungen" f: RR arrow RR}
$
#bold[Lemma 2.30:] Für den $K$-Vektorraum $(V, +, dot)$ mit dem Nullement $0_K$ des Körpers und $0_V$ des Vektorraums. Dann gilt
#box(width: 100%, inset: (right: 1cm, left: 1cm))[
1. $0_K dot v = 0_V$
2. $lambda dot 0_V = 0_V$
3. $-(lambda dot v) = (-lambda) dot v = lambda dot (-v) wide forall space.sixth lambda in K, forall space.sixth v in V$
]
#italic[Beweis:]
zu 1) $forall space.sixth v in V$ gilt
$
0_K dot v &= (0_K + 0_K) dot v = 0_K dot v + 0_K dot v wide bar.v -(0_K dot v) \
0_V &= 0_K dot v + 0_V = 0_K dot v \
0_V &= 0_K dot v
$
zu 2) $forall space.sixth lambda in K$ gilt
$
lambda dot 0_V &= lambda dot (0_V + 0_V) = lambda dot 0_V + lambda dot 0_V wide bar.v -(lambda dot 0_V) \
0_V &= lambda dot 0_V
$
zu 3) $forall space.sixth lambda in K, forall space.sixth v in V$ gilt
$
lambda dot v + ((-lambda) dot v ) = (lambda - lambda) dot v = 0_K dot v = 0_V space checkmark \
lambda dot v + (lambda dot (-v)) = (lambda dot (v - v)) = lambda dot 0_V = 0_V space checkmark
$
#endproof
#definition("2.31", "Untervektorraum")[
Sei $(V, +, dot)$ ein $K$-Vektorraum und sei $U subset.eq V$. Ist $(U, +, dot)$ ein $K$-Vektorraum, so heißt $(U, +, dot)$ ein #bold[Untervektorraum], kurz #bold[Unterraum] von $(V, +, dot)$. \
Wichtig! Die Abgeschlossenheit muss erhalten bleiben.
] <def>
#bold[Lemma 2.32:] Sei $(V, +, dot)$ ein $K$-Vektorraum und $U subset.eq V$. Dann ist $(U, +, dot)$ genau dann ein Unterraum von $V$, wenn gilt:
#box(width: 100%, inset: (left: 1cm, right: 1cm))[
1. $u + w in U wide forall space.sixth u, w in U$
2. $lambda u in U wide forall space.sixth lambda in K, forall space.sixth u in U$
]
#italic[Beweis:] (Übung)
Ist $U$ nicht abgeschlossen bezüglich der Addition und der skalaren Multiplikation, dann ist $(U, +)$ keine kommutative Gruppe und $(U, dot)$ keine Halbgruppe. In beiden Fällen ist $(U, +, dot)$ dann kein Vektorraum und somit auch kein Untervektorraum von $(V, +, dot)$.
#endproof
#bold[Beispiel 2.33:]
#boxedlist[Jeder Vektorraum $(V, +, dot)$ hat die Vektorräume $(U = V, + dot)$ und $(U = {0_V}, +, dot)$][Für jedes $u in NN_0$ ist die Menge aller Polynome mit dem Grad kleiner gleich $n$, d.h. die Menge $P[t]_(<=n) = {p(t) in P[t] | "Grad"(p) <= n}$ mit den Verknüpfungen aus Beispiel 2.28 ein Unterraum von $(P[t], +, dot)$]
#definition("2.34", "Linearkombination")[
Seien $(V, +, dot)$ ein $K$-Vektorraum, $n in NN$ und $v_1, ..., v_n in V$. Ein Vektor der Form
$
lambda_1 v_1 + lambda_2 v_2 + ... + lambda_n v_n = sum_(i = 1)^n lambda_i v_i = v in V
$
heißt #bold[Linearkombination] von $v_1, ..., v_n in V$ mit den Koeffizienten $lambda_1, ..., lambda_n in K$. Die #bold[lineare Hülle] / Der #bold[Spann] von $v_1, ..., v_n in V$ ist die Menge
$
"Span"{v_1, ..., v_n} := {sum_(i=1)^n lambda_i v_i | lambda_1, ..., lambda_n in K}
$
] <def>
#bold[Lemma 2.35:] Sei $(V, +, dot)$ ein $K$-Vektorraum und $v_1, ..., v_n in V$, dann ist $("Span"{v_1, ..., v_n}, +, dot)$ ein Unterraum von $(V, +, dot)$.
#italic[Beweis:] Es gilt $"Span"{v_1, ..., v_n} subset.eq V$. Wegen Lemma 2.32 reicht es zu zeigen, dass $U := "Span"{v_1, ..., v_n}$ bezüglich $+$ und $dot$ abgeschlossen ist. Dies gilt nach der Definition der linearen Hülle.
#endproof
#bold[Beispiel 2.36:] Für $V = RR^3, K = RR$. Betrachte
$
M = {vec(3, 0, 1), vec(9, 0, 3)}, "ist" vec(12, 0, 4) in "Span"(M) "?"
$
Ja, denn es gilt:
$
1 dot v_1 + 1 dot v_2 = vec(3+9, 0+0, 1+3) = vec(12, 0, 4)
$
Des weiteren gilt:
$
"Span"(M) = {lambda dot vec(3, 0, 1) | lambda in RR} = A
$
#italic[Beweis:]
"$subset.eq$":
$A = {vec(3, 0, 1) dot lambda | lambda in RR} subset.eq {lambda dot vec(3, 0, 1) + 0 dot vec(9, 0, 3) | lambda in RR} subset.eq "Span"(M)$
"$supset.eq$":
$
x = vec(x_1, x_2, x_3) in "Span"(M) <==> vec(x_1, x_2, x_3) &= lambda_1 vec(3, 0, 1) + lambda_2 vec(9, 0, 3) \
&= lambda_1 vec(3,0,1) + 3 lambda_2 vec(3, 0, 1) \
&= (lambda_1 + 3 lambda_2) vec(3, 0, 1) \
==> x = (lambda_1 + 3 lambda_2) vec(3, 0, 1) in A
$
#endproof
#pagebreak()
= Basen und Dimensionen von Vektorräumen
Dieses Kapitel motiviert unter anderem die Frage, wie man Vektorräume effizient beschreiben kann.
== Lineare Unabhängigkeit
#definition("3.1", "lineare Unabhängigkeit")[
Sei $V$ ein $K$-Vektorraum. Die Vektoren $v_1, ..., v_n in V$ heißten #bold[linear unabhängig], wenn aus
$
sum_(i = 1)^n lambda_i v_i = 0 wide "mit" lambda_1, ..., lambda_n in K
$
folgt, dass $lambda_1 = lambda_2 = ... = lambda_n = 0$ gilt. Folgt dies nicht, d.h. gilt
$
sum_(i = 1)^n lambda_i v_i = 0 wide "mit" lambda_1, ..., lambda_n in K
$
die nicht alle gleich $0$ sind, so heißten $v_1, ..., v_n$ #bold[linear abhängig].
#boxedlist[Die leere Menge ist linear unabhängig.][Ist $M != emptyset$ eine Menge und für jedes $m in M$ ein Vektor $v_m in V$ gegeben, so nennt man die Menge ${v_m}_(m in M)$ linear unabhängig, wenn endlich viele Vektoren immer linear unabhängig sind. Gilt dies nicht, so ist die Menge ${v_m}_(m in M)$ linear abhängig.]
] <def>
#bold[Bemerkung:] Nach Definition sind die Vektoren $v_1, ..., v_n$ genau dann linear unabhängig, wenn sich der Nullvektor aus ihnen nur in der Form $0 = 0 dot v_1 + ... + 0 dot v_n$ mit endlich vielen Vektoren darstellen lässt
#bold[Beispiel 3.2:] Fortsetzung von Beispiel 2.36
Die Vektoren aus $M = {(3,0,1), (9,0,3)}$ sind linear abhängig, da
$
3 vec(3, 0, 1) - vec(9, 0, 3) = vec(0, 0, 0) wide "mit" lambda_1 = 3, lambda_2 = -1
$
Der Vektor $v_1 = (3, 0, 1)$ dagegen ist linear unabhängig, da
$
0 dot vec(3, 0, 1) = vec(0, 0, 0) wide "mit" lambda_1 = 0
$
#bold[Beispiel 3.3:] $V = RR^3, K = RR$
Betrachte $M = {(3, 0, 1), (9, 0, 3), (0, 1, 1)}$. Sind diese Vektoren linear unabhängig? Die allgemeine Vorgehensweise ist hier, ein lineares Gleichungssystem aufzustellen und zu lösen. Hat das Gleichungssystem eine Lösung $!= 0$, dann sind die Vektoren linear abhängig.
Hier: $==>$ linear abhängig
#bold[Lemma 3.4:] Sei $V$ ein $K$-Vektorraum. Dann gilt:
#box(width: 100%, inset: (left: 1cm, right: 1cm))[
1. Ein einzelner Vektor ist genau dann linear unabhängig, wenn $v != 0_V$ gilt
2. Sind $v_1, ..., v_n in V$ linear unabhängig und ist ${u_1, ..., u_m} subset.eq {v_1, ..., v_n}$, dann ist auch die Menge $u_1, ..., u_m$ linear unabhängig
3. Sind $v_1, ..., v_n in V$ linear abhängig und $u_1, ..., u_m in V$. Dann ist auch $v_1, ..., v_n, u_1, ..., u_m$ linear abhängig
]
#italic[Beweis:]
zu 1: Sei $v in V, v != 0_V$. Es soll gelten: $lambda v = 0 ==> lambda = 0, "da" v != 0_V$
zu 2: $v_1, ..., v_n$ sind linear unabhängig und es gilt ${u_1, ..., u_m} subset.eq$ ${v_1, ..., v_n}$.
Damit die Vektoren ${u_1, ..., u_m}$ linear unabhängig sind, muss gelten
$
lambda_1 u_1 + ... + lambda_m u_m = 0 ==> u_1 = ... = u_m = 0
$
Wegen der linearen Unabhängigkeit von ${v_1, ..., v_n}$ gilt nach Umbennenung der Vektoren ${u_1, ..., u_m}$:
$
lambda_i_1 v_i_1 + ... + lambda_i_m v_i_m + limits(sum_(j = 1)^n)_(j in.not {i_1, ..., i_m}) v_j = 0 ==> lambda_i_1 = ... = lambda_i_m = 0
$
zu 3: $v_1, ..., v_n$ sind linear abhängig $==> exists space.sixth lambda_i in K$, so dass nicht alle $lambda_i$ gleich Null sind und $lambda_1 v_1 + lambda_2 v_2 + ... + lambda_n v_n = 0$ gilt.
$==> lambda_1 v_1 + ... + lambda_n v_n + mu_1 u_1 + ... + mu_m u_m = 0$ $==> mu_1, ..., mu_m = 0$ $==>$ Mit Koeffizienten $lambda_1, ..., lambda_n, mu_1, mu_m$ lassen sich $v_1, ..., v_n, u_1, ..., u_m$ linear zu Null kombinieren ohne, dass alle Koeffizienten Null sind $==> v_1, ..., v_n, u_1, ..., u_m$ sind linear abhängig
#endproof
Eine alternative Definition der linearen Unabhängigkeit motiviert Satz 3.5:
#bold[Satz 3.5:] Sei $V$ ein $K$-Vektorraum. Eine Menge $M subset.eq V$ ist genau dann linear unabhängig, wenn kein Vektor $v in M$ als Linearkombination der anderen Vektoren dargestellt werden kann.
#italic[Beweis:]
"$==>$": Annahme: $M subset.eq V$ sind linear unabhängig und es existiert ein Vektor $v in M$, der als Linearkombination von endlichen Vektoren aus $M backslash {v}$ dargestellt werden kann. D.h. es existieren $lambda_1, ..., lambda_n in K backslash {0}, n >= 1$ und $v_1, ..., v_n in M backslash {v}$ mit
$
sum_(i = 1)^n lambda_i v_i = v ==> -v + sum_(i = 1)^n lambda_i v_i = 0 space arrow.zigzag
$
Dies ist ein Widerspruch zur Annahme, dass die Vektoren linear unabhängig sind. Es existiert also kein Vektor, welcher als Linearkombination ausgedrückt werden kann.
"$<==$": Angenommen $M$ wäre linear abhängig. D.h. es existieren $n in NN$ und $v_1, ..., v_n in M, lambda_1, ..., lambda_n in K$ mit $lambda_1 != 0 "und" sum_(k = 1)^n lambda_k v_k = 0$ $==>$
$
sum_(k = 1)^n lambda_k/lambda_1 v_k = 0 ==> v_1 + sum_(k = 2)^n lambda_k/lambda_1 v_k = 0 \
==> v_1 = -sum_(k = 2)^n lambda_k/lambda_1 v_k space arrow.zigzag
$
Dies ist ein Widerspruch dazu, dass man $v$ nicht als Linearkombination darstellen kann. Die Vektoren sind also linear unabhängig.
#endproof
#definition("3.6", "Span für unendliche Mengen")[
Sei $K$ ein Körper, $V$ ein $K$-Vektorraum, $M$ eine Menge und $v_m in M space forall space.sixth m in M$ gegeben. Dann ist der Spann der Familie ${v_m}_(m in M)$ gegeben durch
$
"Span"{v_m}_(m in M) := {#box(width: auto, height: 0.7cm, [
$
v in V | exists space.sixth n in NN "und endliche Teilmenge" J subset M, \
abs(J) = n "mit" v in "Span"{v_j}_(j in J)
$
])}
$
] <def>
#bold[Beispiel 3.7:] $M = NN$, $v_m := t^m$, $t in K$, $"Span"{v_m}_(m in M) = P[t]$
#bold[Satz 3.8:] Sei $K$ ein Körper, $V$ ein $K$-Vektorraum und $M$ eine Menge. Dann sind folgende Aussagen äquivalent:
#box(width: 100%, inset: (left: 1cm, right: 1cm))[
1. ${v_m}_(m in M)$ ist linear unabhängig
2. jeder Vektor $v in "Span"{v_m}_(m in M)$ hat eine eindeutige Darstellung als Linearkombination
]
#italic[Beweis:]
$1 ==> 2$: Beweis per Kontraposition
Seien $I, J subset.eq M$ endlich. Sei $lambda_K in K$, $k in I$ und $mu_k in K$, $k in J$. Betrachte den Vektor $v in V$. Für diesen gilt:
$
v_I = sum_(k in I) lambda_k v_k "und" v_J = sum_(k in J) mu_k v_k
$
Überlegung: Wähle ein $k in I union J$. Falls gilt $k in I backslash J$, setze $lambda_k = 0$. Falls gilt $k in J backslash I$, setze $mu_k = 0$. Es folgt
$
==> 0 = sum_(k in I union J) (lambda_k - mu_k) v_k
$
Da die Darstellung $v_I$ und $v_J$ von $v$ unterschiedlich sind, existiert ein $k in I union J$ mit $lambda_k - mu_k != 0$.
$
==> {v_m}_(m in M) "ist linear abhängig"
$
$2 ==> 1$: Beweis per Kontraposition
Angenommen ${v_m}_(m in M)$ wäre linear abhängig. Dann existiert ein endliches $J subset.eq M$ und $lambda_k in K$ für $k in J$ mit $0 = sum_(k in J) lambda_k v_k$ und mindestens ein $lambda_k != 0$.
Sei $v in "Span"{v_m}_(m in M)$, d.h. es existiert ein endliches $I subset.eq M$ mit $mu_k in K$ für alle $k in I$ mit
$
v = sum_(k in I) mu_k v_k ==> v + 0 = sum_(k in I) mu_k v_n + sum_(k in J) lambda_k v_k = sum_(k in I union J) (mu_k + lambda_k) v_k
$
Es gilt wieder $mu_k = 0$ für $k in J backslash I$ und $lambda_k = 0$ für $k in I backslash J$. Da für mindestens ein $k in J union I$, $(mu_k + lambda_k) != lambda_k$, ist dies eine zweite Darstellung von $v$.
#endproof
#definition("3.9", "Erzeugendensystem")[
Sei $K$ ein Körper, $V$ ein $K$-Vektorraum, $M$ eine Menge und $v_m$ für $m in M$ Vektoren in $V$. Die Menge ${v_m}_(m in M)$ heißt #bold[Erzeugendensystem] von $V$, falls
$
"Span"{v_m}_(m in M) = V
$
] <def>
#bold[Beispiel 3.10:] Sei $K$ ein Körper, $V$ ein Vektorraum mit $V = K^n$, $n in NN$
Dann ist mit
$
e_1 := vec(1, 0, dots.v, 0), space e_2 := vec(0, 1, dots.v, 0), space ..., space e_n := vec(0, 0, dots.v, 1)
$
die Menge ${e_i}_(in in {1, ..., n})$ ein Erzeugendensystem von $K^n$.
#definition("3.11", "Basis")[
Sei $K$ ein Körper, $V$ ein $K$-Vektorraum, $M$ eine Menge und $v_m$ für $m in M$ Vektoren in von $V$. Dann heißt ${v_m}_(m in M)$ #bold[Basis] von $V$, falls sie linear unabhängig und ein Erzeugendensystem von $V$ ist.
] <def>
#bold[Beispiel 3.12:] Das Erzeugendensystem aus 3.10 ist eine Basis. Anmerkung: Basen sind nicht eindeutig. Für $K^3$ gilt etwa
$
v_1 = vec(1,1,0) space v_2 = vec(1,0,1) space v_3 = vec(0, 1, 1)
$
ist ebenfalls eine Basis.
#bold[Beispiel 3.13:] Die Familie ${t^i}_(i in NN)$ ist ein Erzeugendensystem von $P[t]$, denn es gilt $"Span"{t^i}_(i in NN) = P[t]$. Um zu prüfen, ob die Familie auch Basis von $P[t]$ muss die lineare Unabhängigkeit gerpüft werden. Sei $n in NN_0$, $a_0, a_1, ..., a_n in K$ und betrachte $p(t) = a_0 + a_1 t + ... + a_n t^n$ mit $p(t) = 0$.
Falls $a_k != 0$ für ein $k in {0, ..., n}$ gilt, so hat $p(t)$ höchstens $n$ Nullstellen in $K$. $0 in P[t]$ hat aber unendlich viele Nullstellen. D.h. es existiert ein $t in K$ mit $p(t) != 0 space arrow.zigzag$. Es folgt, dass die Familie ${t^i}_(i in NN)$ linear unabhängig ist. Somit ist ${t^i}_(i in NN)$ eine Basis von $P[t]$.
#bold[Satz 3.14:] Sei $K$ ein Körper, $V$ ein Vektorraum und $B := {v_1, ..., v_n} subset.eq V$. Dann ist äquivalent
#box(width: 100%, inset: (left: 1cm, right: 1cm))[
1. $B$ ist eine Basis #h(1fr)
2. $B$ ist ein unverkürzbares Erzeugendensystem, d.h. $forall r in {1, ..., n}$ ist die Menge $B backslash {v_r}$ kein Erzeugendensystem von $V$
3. Für alle $v in V$ existieren eindeutige $lambda_1, ..., lambda_n$ mit
$
v = sum_(k = 1)^n lambda_k v_k
$
4. $B$ ist unverlängerbar linear unabhängig. D.h. für alle $v in V without B$ ist $B union {v}$ linear abhängig
]
#italic[Beweis:]
$1 ==> 2$: Beweis durch Kontraposition
Angenommen $B$ ist ein verkürzbares Erzeugendensystem. D.h. o.B.d.A $r = 1$, $B backslash {v_1}$ ist auch ein Erzeugendensystem von $V$. Also existieren $lambda_2, ..., lambda_n in K$ mit
$
v_1 = sum_(k = 2)^n lambda_k v_k
$
Mit Satz 3.5 folgt, dass $B$ linear abhängig ist. Also ist $B$ keine Basis.
$2 ==> 3$: Beweis durch Kontraposition
Angenommen, es existiert $v in V$, $lambda_k, mu_k in K$ mit
$
v = sum_(k = 1)^n lambda_k v_k "und" v = sum_(k = 1)^n mu_k v_k
$
o.B.d.A gilt $mu_1 != lambda_1$. Dann folgt $0 = sum_(k = 1)^n (lambda_k - mu_k) v_k$.
Weiterhin gilt
$
0 = sum_(k = 1)^n (lambda_k -mu_k)/(lambda_1 - mu_1) v_k ==> v_1 = sum_(k = 2)^n -(lambda_k - mu_k)/(lambda_1 - mu_1) v_k
$
Sei nun $w in V$, dann existiert ein $alpha_k in K$ mit
$
w = sum_(k = 1)^n alpha_k v_k = alpha_1 v_1 + sum_(k = 2) alpha_k v_k = star
$
Wir defnieren
$
beta_k = -(lambda_k - mu_k)/(lambda_1 - mu_1)
$
Dann gilt
$
star = sum_(k = 2)^n (alpha_1 beta_k + alpha_k) v_k
$
Also war $B$ kürzbar.
$3 ==> 4$:
Satz 3.8 liefert, dass $B$ linear unabhängig ist. Sei $v in V backslash B$. Dann existieren $lambda_1, ..., lambda_k in K$ mit
$
v = sum_(k = 1)^n lambda_k v_k
$
Das heißt $B union {v}$ ist linear abhängig nach Satz 3.8.
$4 ==> 1$:
Sei $B$ unverlängerbar linear abhängig. Sei $v in V without B$. Dann ist $B union {v}$ linear abhängig. Also existiert $lambda_1, ..., lambda_n, lambda in K$ mit
$
0 = sum_(k = 1)^n lambda_k v_k + lambda v "wobei nicht alle" lambda_k, lambda = 0
$
Da $B$ linear unabhängig ist folgt $lambda != 0$. Daraus folgt
$
v = sum_(k = 1)^n -lambda_k/lambda v_k
$
Also ist $B$ ein Erzeugendensystem und somit eine Basis.
#endproof
#definition("3.15", "endlichdimensional, unendlichdimensional")[
Sei $(V, +, dot)$ ein $K$-Vektorraum für den eine endliche Menge $M = {v_1, ..., v_n} subset V$ existiert, so dass $"Span" M = V$. Dann nennt man $V$ #bold[endlich erzeugt] und sagt $V$ ist #bold[endlichdimensional]. Ist $V$ nicht von endlich vielen Vektoren erzeugt, nennt man $V$ #bold[unendlichdimensional].
] <def>
#bold[Beispiel 3.16:]
#boxedlist[
Die Einheitsvektoren aus Beispiel 3.10 sind eine Basis des $K^n$ für einen Körper $K$. Damit ist $K^n$ endlich erzeugt.
][
Der Vektorraum $P[t]$ der Polynome aus Beispiel 3.13 ist über dem Körper $K$ mit der Basis ${t^i}_(i in NN_0)$ ist nicht endlich erzeugt.
][
Sei $V$ der Vektorraum der stetigen reellwertigen Funktionen auf dem Intervall $[0, 1]$. Dann ist $V$ unendlichdimensional, denn:
Sei für $n in NN$ die Funktion $f_n in V$ definiert durch
$
f_n: [0, 1] -> RR, space x arrow.bar cases(0"," &0 <= x <= 1/(n+1), 2n(n+1)x-2n"," &1/(n+1)<=x<=1/2(1/n + 1/(n+1)), -2(n+1)x+2n+2"," wide&1/2(1/n + 1/(n+1)), 0"," &1/n <=x<=1)
$
Es gilt für jede Linearkombination der $f_n$ und $j, k in NN$ mit $j <= k$, dass
$
sum_(j = 1)^k lambda_j f_j (1/2(1/j + 1/(j+1))) = lambda_j "bei" f_j = 1", sonst" 0
$
Damit ist:
$
sum_(i = 1)^k lambda_i f_i (x) = 0_v in V, space forall x in [0, 1]
$
nur erfüllt, wenn $lambda_i = 0$ für alle $1 <= i <= k$. Damit sind die $f_n$ linear unabhängig. Also ist $V$ unendlichdimensional.
]
#bold[Frage:] Hat jeder Vektorraum eine Basis?
Diese Frage ist relativ einfach im endlichdimensionalen Fall:
#bold[Lemma 3.17:] Basisauswahlsatz
Ein $K$-Vektorraum $(V, +, dot)$ ist genau dann endlich, erzeugt, wenn er eine endliche Basis besitzt.
#italic[Beweis:]
"$<==$": endliche Basis $==>$ endliches Erzeugendensystem $==>$ endlich erzeugt
"$==>$": Sei $V$ endlich erzeugt $==> exists v_1, ..., v_n: "Span"{v_1, ..., v_n} = V$. Ist dieses Erzeugendensystem nicht minimial, d.h. linear abhängig, dann folgt mit Satz 3.5, dass ein $v_i, 1 <= i <= n$, als Linearkombation der anderen $v_j, i != j$ dargestellt werden kann. Entfernen des $v_i$ liefert ein kleineres Erzeugendensystem. Wiederhole $n-1$-Mal, bis die verbleibende Menge linear unabhängig ist. Somit enthält jedes endliche Erzeugendensystem ein minimales Erzeugendensystem und somit eine Basis.
#endproof
Für den unendlichdimensionalen Fall ist mehr Arbeit nötig:
#bold[Satz 3.18:] Jeder $K$-Vektorraum $(V, +, dot)$ besitzt eine Basis (ein minimales Erzeugendensystem).
#italic[Beweis:]
Idee: Wir wenden das zornsche Lemma auf $M = V$ und \ $cal(S) = {A subset.eq V | "die Familie" {v}_(v in A) "ist linear unabhängig"} subset.eq cal(P)(M)$
Dazu treffen wir die Annahme, dass die Vorraussetzungen für das Zornsche Lemma gelten. Dann hat $cal(S)$ ein maximales Element bezüglich der Relation $<=$.
Da maximal linear unabhängige Familien von Vektoren aus $V$ Basen von $V$ sind (Satz 3.14), ist damit die Behauptung gezeigt.
Jetzt müssen wir die Verwednung des Zornschen Lemmas rechtfertigen.
Für $cal(K) subset.eq cal(S)$, $cal(K)$ ist eine Kette, gilt $union.big_(A in cal(K)) A in cal(S)$. Sei $cal(K) subset.eq cal(S)$ seine Kette. zu zeigen:
$
B := union.big_(A in cal(K)) A in cal(S)
$
D.h. die Vektoren aus $B$ sind eine Menge von linear unabhängigen Vektoren. Seien dazu endlich viele Vektoren $v_1, ..., v_n in B$ beliebig vorgegeben. Per Definition von $B$ existiert in der gegebenen Kette $cal(K)$ für jeden Index $i in {1, ..., n}$ eine Menge $A_i in cal(K)$ mit $v_i in A_i$.
Nach Lemma 1.26 über endliche Teilmengen von Ketten gibt es einen Index $tilde(dotless.i) "mit" A_i subset.eq A_tilde(dotless.i)$ für alle $i$. $==>$ alle Vektoren $v_1, ..., v_n in A_tilde(dotless.i) in cal(S)$. Daraus folgt, dass ${v_1, ..., v_n}$ linear unabhängig ist.
#endproof
== Basen
Man kann eine Basis als Koordinatensystem in einem Vektorraum auffassen. Wichtig ist, dass Basen nicht eindeutig sind (vergleiche Beispiel 3.12). Eine sehr wichtige Frage der linearen Algebra ist: Welche Basis wählt man?
#bold[Beispiel 3.19:] Um aus einer im Verhältnis $1:1$ in Wasser gelösten Substanz eine Lösung im Mischungsverhältnis $a:b$ zu bekommen, verdünnt man $y$ Teile der Lösung mit $x$ Teilen Wasser, so dass
$
x dot vec(1,1) + y dot vec(1,0) = vec(a, b) wide x"-Koordinate ist Wasser," y"-Koordinate ist Substanz"
$
Eine andere Darstellung der Basis ist
$
vec(1, 1/2) &= 1 dot e_1 + 1/2 dot e_2 = 1 dot vec(1,0) + 1/2 dot vec(0,1) \
&= 1/2 v_1 + 1/2 v_2 = 1/2 vec(1,1) + 1/2 vec(1,0)
$
Man sieht:
#boxedlist[$1$ Parameter in $RR^1$][$2$ Parameter in $RR^2$][$3$ Parameter in $RR^3$]
#bold[Ziel:] Alle Basen eines endlich erzeugten Vektorraums haben gleich viele Elemente.
#align(center, [Das ist durchaus nicht offensichtlich#bold[!!!]])
#bold[Beispiel 3.20:] Es gibt eine bijektive Abbildung $f: NN -> NN times NN$. Dafür kann man z.B. das Diagonalargument von Georg Cantor verwenden.
Zum Beweis der Aussage sind noch Vorarbeiten notwendig.
#bold[Satz 3.21:] Basisergänzungssatz
Sei $(V, +, dot)$ ein $K$-Vektorraum,
#boxedlist[${u_i}_(i in I) subset.eq V$ ein linear unabhängiges System][${v_j}_(j in J) subset.eq V$ ein Erzeugendensystem von $V$]
Dann gibt es eine Teilmenge $tilde(J) subset.eq J$ mit der Eigenschaft, dass das System
$
B := {w_k}_(k in I union tilde(J)) "mit" w_k := cases(u_i"," space &k = i in I, v_j"," space &k = j in tilde(J))
$
eine Basis von $V$ bildet.
#italic[Beweis:] Sei $tilde(J) subset.eq J$ eine bezüglich $subset.eq$ maximal gewählte Teilmenge mit der Eigenschaft, dass $B$ wie im Satz definiert, ein linear unabhängiges System ist. Für endliche Mengen $J$ ist das klar (siehe Lemma 3.17). Für Mengen mit unendlich vielen Elementen folgt dies aus dem zornschen Lemma (Satz 3.18). Damit: $B$ ist ein maximales linear unabhängiges System.
Wegen der Maximalität ist für jeden Index $j in J backslash tilde(J)$ das System $B union {v_j}$ linear abhängig
$==> exists lambda, lambda_i in K, i in I union tilde(J):$
$
lambda dot v_j + sum_(i in I union tilde(J)) lambda_i dot v_i = 0
$
wegen der linearen Unabhängigkeit der ${v_i}_(i in I union tilde(J))$ muss $lambda != 0$ gelten
$
==> v_j = - sum_(i in I union tilde(J)) lambda_i / lambda dot w_i in "Span" B
$
Dies gilt für alle $j in J backslash tilde(J) ==> v_j in "Span" B space forall j in J ==> B "Basis"$
#endproof
#bold[Beispiel 3.22:] In $V = RR^3$ bilden die Vektoren ${e_1, e_2, e_3}$ die Standardbasis. Des Weiteren sind die Vektoren $u_1= (3, 1, 0) "und" u_2 = (1, 3, 0)$ linear unabhängig. Satz 3.21 liefert, dass ${u_1, u_2, e_3}$ eine Basis ist.
#bold[Satz 3.23:] Austauschsatz von Steinitz
(Ernst Steinitz, deutscher Mathematiker, 1871 - 1928)
Sei $(V, +, dot)$ ein $K$-Vektorraum,
#boxedlist[$B = {v_1, ..., v_n}$ eine (endliche) Basis][$C = {u_1, ..., u_m}$ eine linear unabhängige Familie]
Dann ist $m <= n$ und nach geeigneten umnummerieren der Vektoren in $B$ ist das durch austauschen der ersten $m$-Vektoren erhaltene System
$
tilde(B) := {u_1, ..., u_m, v_(m+1), ..., v_n} "eine Basis von" V "über" K
$
#italic[Beweis:] Aus dem Basisergänzungssatz folgt, dass man das linear unabhängig System $u_1, ..., u_m$ zu einer Basis $u_1, ..., u_m, v_j_1, ..., v_j_k_0$ für ein $k_0 >= 0$ und geeignete Indizes $j_1, ..., j_k_0 in {1, ..., n}$ erweitern kann.
Die Menge ${u_1, ..., u_(m-1), v_j_1, ..., v_j_k_0}$ ist immer noch linear unabhängig aber keine Basis. Aus dem Basisergänzungssatz folgt wieder, dass man diese Menge zu einer Basis ${u_1, ..., u_(m-1), v_j_1, ..., v_j_k_0, v_j_(k_0 + 1), ..., v_j_k_1}$ für ein $k_1 > k_0$ und weitere Indizes $j_(k_0 + 1), ..., v_k_1 in {1, ..., n}$. Setzt man dieses Verfahren induktiv $v$-mal fort, erhält man im $r$-ten Schritt eine Basis ${u_1, ..., u_(m - r), v_j_1, v_j_2, ..., v_j_k_(r - 1), v_j_(k_(r-1)+1), ...., v_j_k_r}$ für ein $k_r > k_(r-1)$ und weitere Indizes $j_(k_(r-1)+1), ..., j_k_r in {1, ..., n}$. Nach $m$ Schritten sind alle $u_i, 1 <= i <= m$ ersetzt.
Als neue Basis erhält man
$
hat(B) := {v_j_1, ..., v_j_m}
$
welche ausschließlich Vektoren aus $B$ enthält. $B$ war ein minimales Erzeugendensystem. Also muss die neue Menge $hat(B)$ bis auf die Umordnung mit der Menge $B$ übereinstimmen. Für die Menge der Indizes gilt also:
$
hat(B) = {v_j_1, ..., v_j_k_m} = {v_1, ..., v_n} = B
$
Also folgt: $k_m = n$
Wir haben jeweils mindestens einen Vektor ergänzt, d.h.
$
k_m > k_(m-1) > ... > k_1 > 0 ==> k_m >= m ==> n = k_m >= m ==> n >=m ==> "erste Aussage"
$
Dann folgt die zweite Aussage aus dem Basisergänzungssatz.
#endproof
#bold[Lemma 3.24:] Ist $(V, +, dot)$ ein von endlich vielen Vektoren erzeugter $K$-Vektorraum, so besitzt $V$ eine endliche Basis und je zwei Basen von $V$ haben gleich viele Elemente.
#italic[Beweis:] Sei $V = "Span"{v_1, ..., v_n}$ mit $v_1 != 0$. Nach Satz 3.21 kann ${v_1}$ durch Hinzunahme von geeigneten Elementen aus ${v_2, ..., v_n}$ zu einer Basis von $V$ ergänzen. Also besitzt $V$ eine Basis mit endlich vielen Elementen.
Seien $U = {u_1, ..., u_l} "und" W = {w_1, ..., w_k}$ zwei solche Basen. Dann folgt aus dem Satz 3.23 aus Symmetrie, dass $k = l$.
#endproof
#bold[Ausblick:] Man kann mit Konzepten der Mengenlehre auch zeigen, dass es für unendlich erzeugte Vektorräume $V$ gilt: Für je zwei Basen ${u_i}_(i in I)$ und ${w_j}_(i in J)$ von $V$ existiert eine bijektive Abbildung $f: I -> J$.
Folgerung aus Satz 3.8 in Zusammenhang mit Lemma 3.24: Da für eine Basis $B := {v_1, ..., v_n}$ eines $K$-Vektorraums $V$ gilt, dass $"Span" B = V$, sind für $v in V$ die Koeffizienten (= Koordinaten) $lambda_1, ..., lambda_n$ zur Darstellung von $v$ eindeutig.
#bold[Beispiel 3.25:] für $V = RR^3$ sind
$
B_1 := {vec(1, 0, 0), vec(0, 1, 0), vec(0, 0, 1)} "und" B_2 := {vec(-2, -1, 0), vec(-2, 3, 0), vec(-5, 0, 2)}
$
zwei Basen. Der Vektor $v = (-5, 11, 2)$ besitzt bezüglich $B_1$ die Koordinaten $lambda_1 = -5, lambda_2 = 11, lambda_3 = 2$. Was sind die Koordinaten bezüglich $B_2$? Es muss gelten:
$
a vec(2, -1, 0) + b vec(-2, 3, 0) + c vec(-5, 0, 2) = vec(-15, 11, 2)
$
anders kann man dies notieren als
$
vec(2a - 2b - 5c, -a + 3b + 0c, 0a + 0b + 2c) = vec(-15, 11, 2)
$
Berechnung der $a, b, c$ über ein lineares Gleichungssystem ergibt $a = 2, b = 3, c = 1$.
#bold[Beispiel 3.26:] Für den $RR$-Vektorraum $P_(<= 2)[t]$ der reellen Polynome vom Grad $<= 2$ sind:
$
B_1 := {1, t, t^2} "und" B_2 := {-t, t^2 - 2, t^2 + 2}
$
zwei Basen. Sei $p(t) = a + b t + c t^2$ ein beliebiges Polynom aus $P_(<= 2)[t]$. Dann sind die Koeffizienten für $B_1: lambda_1 = a, lambda_2 = b, lambda_3 = c$. Für $B_2$ gilt:
$
"Basiswechsel, siehe Kapitel" 4 space space cases(1 = -1/4(t^2-2)+1/4(t^2+2), t = (-1)(-t), t^2 = 1/2(t^2+2)+1/2(t^2-2))
$
Es gilt
$
a 1 + b t + c t^2 &= a(-1/4(t^2-2)+1/4(t^2+2)) + b(-1)(-t) + c(1/2(t^2+2)+1/2(t^2-2)) \
&= -b(-t) + (-a/4 + c/2)(t^2-2) + (a/4 + c/2)(t^2+2)
$
== Dimensionen
#definition("3.27", "Dimension eines Vektorraums")[
Die Dimension eines Vektorraum $(V, +, dot)$ über $K$ ist definiert als:
$
dim_K (V) := cases(n &"falls" V "eine Basis der Länge" n "hat", infinity &"sonst")
$
Wenn der Kontext klar ist schreibt man $dim V$.
] <def>
#bold[Beispiel 3.28:] Sei $K$ ein Körper. Es gilt
#boxedlist[$dim_K (V) = 0$ genau dann, wenn $V = {0}$][
für $V = K^n$ folgt mit der Standardbasis, dass $dim_K (V) = n$][für die Dimension eines Vektorraums ist der jeweilige Grundkörper $K$ entscheident, z.B. $CC$ und $K = CC$ gilt $dim_CC V = 1$ für $K = RR$ aber $dim_RR V = 2$.
][der $K$-Vektorraum $P[t]$ ist nicht endlich erzeugt, also $dim_K P[t] = infinity$]
#bold[Beispiel 3.29:] Sei $V = K^n$ für einen Körper $K$. Um zu prüfen, dass $n$ Vektoren aus $V$ eine Basis werden, muss nur deren lineare Unabhängigkeit geprüft werden. Seien z.B. $B$ in $V = RR^3$ die Vektoren
$
v_1 = vec(2, -1, 0) space v_2 = vec(-2, 3, 0) space v_3 = vec(-5, 0, 2)
$
gegeben. Sind diese linear unabhängig?
$
lambda_1 vec(2, -1, 0) + lambda_2 vec(-2, 3, 0) + lambda_3 vec(-5, 0, 2) attach(=, t: !) vec(0,0,0)
$
Dazu wird ein lienares Gleichungssystem aufgestellt
$
vec(2a - 2b - 5c, -a + 3b + 0c, 0a + 0b + 2c) = vec(0,0,0)
$
$==> a = 0, b = 0, c = 0$.
Somit sind die Vektoren linear unabhängig.
#bold[Lemma 3.30:] Sei $(V, +, dot)$ ein $K$-Vekorraum mit $n := dim_K V < infinity$ und $B = {v_1, ..., v_n} subset V$ eine Familie von genau $n$ Vektoren. Dann sind folgende Aussagen äquivalent:
#box(width: 100%, inset: (left: 1cm, right: 1cm))[
1. $B$ ist eine Basis
2. $B$ ist linear unabhängig
3. $B$ ist ein Erzeugendensystem
]
#italic[Beweis:] (Übungsaufgabe, Blatt 8, Aufgabe 1)
$1 ==> 2 "und" 1 ==> 3$: Folgt direkt aus der Definition einer Basis.
$2 ==> 1$: Angenommen $B$ ist keine Basis von $V$. Da $B$ linear unabhängig ist, kann $B$ kein Erzeugendensystem von $V$ sein. Mit dem Basisergänzungssatz (Satz 3.21) lässt sich das linear unabhängige System $B$ mit Vektoren eines Erzeugendensystems von $V$, wir wählen $V$ selbst, zu einer Basis $B'$ ergänzen. Definiere die $B'$ wie folgt:
$
B' = B union {v_(n+1), ..., v_(n + k)}, wide v_(n+1), ..., v_(n + k) in V backslash B
$
Dann hat $B$ mit Sicherheit mehr als $n$ Elemente. Dies ist ein Widerspruch dazu, dass die Dimension des Vektorraums $n$ ist (Definition 3.27 und Lemma 3.24). Die Annahme muss also falschs sein. $==>$ $B$ ist eine Basis von $V$.
$3 ==> 1$: Angenommen $B$ ist keine Basis von $V$. Da $B$ ein Erzeugendensystem ist, kann $B$ nicht linear unabhängig sein. Daraus folgt, dass $B$ zu einem minimalen Erzeugendensystem, also einer Basis $B'$ verkürzbar ist. Definiere $B'$ wie folgt:
$
B' = B backslash {v_n_0, ..., v_n_k}, wide v_n_0, ..., v_n_k in B
$
Dann hat $B'$ mit Sicherheit weniger als $n$ Elemente. Dies ist ein Widerspruch dazu, dass die Dimension des Vektorraums $n$ ist. Die Annahme muss also falsch sein. $==>$ $B$ ist eine Basis von $V$.
#endproof
#bold[Lemma 3.31:] Sei $(V, +, dot)$ ein endlich erzeugter $K$-Vektorraum. Jeder Untervektorraum $W subset.eq V$ ist dann ebenfalls endlichdimensional und es gilt:
$
dim W <= dim V
$
mit Gleichheit genau dann, wenn $W = V$.
#italic[Beweis:] jede linear unabhängige Familie in $W$ ist auch linear unabhängig in $V$. Damit besteht sie nach dem Austauschsatz von Steinitz aus höchstens $dim_K V$ Elementen. Daraus folgt, dass $W$ endlich erzeugt ist mit $dim_K W <= dim_K V$. Im Fall von $dim_K W = dim_K V$ folgt mit Lemma 3.30, dass jede Basis von $W$ auch eine Basis von $V$ ist. $==>$ $V = W$
#endproof
#bold[Achtung:] Die letzte Aussage (d.h. $V = W$) gilt nicht für unendlich erzeugte Vektorräume. Denn der $K$-Vektorraum $P[t]$ aller Polynome hat die Basis der Monome ${t^n}_(n in NN_0)$. Die Menge aller Polynome aus $P[t]$ mit $a_0 = 0$ ist ein Unterraum mit der Basis ${t^n}_(n in NN)$ und wird mit $W$ bezeichnet. Dann gilt
$
dim_K P[t] = infinity = dim_K W, "aber" P[t] != W
$
== Direkte Summen
Aus der Definition von Mengenoperationen aus dem ersten Kapitel folgt: sind $U_1 "und" U_2$ zwei Unterräume des $K$-Vektorraums $(V, +, dot)$, so gilt für ihren Durchschnitt:
$
U_1 sect U_2 = {u in V | u in U_1 and u in U_2}
$
#definition("3.32", "Summe von Mengen")[
Sei $(V, +, dot)$ ein $K$-Vektorraum für die Unterräume $U_1, ..., U_r subset.eq V$ definiert man ihre Summe als die Teilmenge
$
U_1 + U_2 + ... + U_r := {u_1 + u_2 + ... + u_r | u_i in U_i "für" 1 <= i <= r} subset.eq V
$
] <def>
Für den Durchschnitt und die Summe von Untervektorräumen gelten folgende Regeln:
#bold[Lemma 3.33:] Sind $U_1, U_2, U_3$ Unterräume des $K$-Vektorraums $(V, +, dot)$, dann gilt:
#box(width: 100%, inset: (left: 1cm, right: 1cm))[
1. $U_1 sect U_2$ und $U_1 + U_2$ sind Unterräume von $V$
2. $U_1 + (U_2 + U_3) = (U_1 + U_2) + U_3 "und" U_1 + U_2 = U_2 + U_1$
3. $U_1 + {0} = U_1$ und $U_1 + U_1 = U_1$
4. $U_1 subset.eq U_1 + U_2$ mit Gleichheit, d.h. $U_1 = U_1 + U_2$, wenn $U_2 subset.eq U_1$
]
#italic[Beweis:] (Übungsaufgabe)
#endproof
#bold[Beispiel 3.34:] Sei $V := RR^3, U_1 := "Span"{(1, 0, 0), (0, 1, 0)}, U_2 := {(0, 1, 0), (0, 0, 1)}$. Dann gilt für $v in V, v = (v_1, v_2, v_3)$
$
v = v_1 vec(1,0,0) + v_2 vec(0,1,0) + v_3 vec(0,0,1)
$
Also gilt: $U_1 + U_2 = V$, insbesondere gilt auch $dim(U_1 + U_2) = 3$, $dim U_1 = 2 = dim U_2$. Weiterhin gilt
$
v_1 vec(1,0,0) in U_1 "und" v_2 vec(0, 1, 0) + v_3 vec(0, 0, 1) in U_2
$
Also ist die Darstellung von $v$ als Summe #bold[nicht] eindeutig. Insbesondere ist $dim(U_1 sect U_2) = 1$.
#bold[Lemma 3.35:] Sei $V$ ein $K$-VR und $r in NN$ und $U_1, ..., U_r$ Untervektorräume von $V$. Dann sind folgende Aussagen äquivalent.
#box(width: 100%, inset: (left: 1cm, right: 1cm))[
1. Für $u in sum_(i = 1)^r U_i$ existieren eindeutige $u_i in U_i$, $i in {1, ..., r}$ mit $u = sum_(i = 1)^r u_i$
2. #[
Für $u_i in U_i$, $i in {1, ..., r}$ mit $0 = limits(sum_(i=1)^r) u_i$ gilt
$
u_i = 0 wide i in {1, ..., r}
$
]
3. #[
Für $i in {1, ..., r}$ gilt
$
U_i sect limits(sum_(j = 1)^r)_(j != i) U_j = {0_V}
$
]
]
#italic[Beweis:] (Übungsaufgabe, Blatt 9, Aufgabe 1)
$1 ==> 2$:
Eine Darstellung des Nullvektors ist $0 = 0_1 + ... 0_r$ mit $0_i in U_i$. Da jeder Vektor eine eindeutige Darstellung bestizt, folgt 2).
$2 ==> 3$: Beweis durch Kontraposition
Angenommen es gilt $U_i sect limits(sum_(j = 1)^r)_(j != i) u_i != {0_V}$. Dann existiert ein Vektor $v$ mit $v in U_i$ und $v in U_1 + ... + U_(i-1) + U_(i+1) + ... + U_r$. Da $U_i$ und $U_1 + ... + U_(i-1) + U_(i+1) + ... + U_r$ Untervektorräume von $V$ bilden, gilt auch $-v in U_i$ und $-v in U_1 + ... + U_(i-1) + U_(i+1) + ... + U_r$. Daraus folgt
$
sum_(j = 1)^r u_j = v + limits(sum_(j = 1)^r)_(j != i) u_i = v + (-v) = 0
$
Somit gilt
$
sum u_i = 0 "aber" u_j != 0, j in {1, ..., r}
$
$3 ==> 1$: Beweis durch Kontraposition
Angenommen ein Vektor $v in V$ besitzt keine eindeutige Darstellung. Dann gilt für ein $u in U_i$:
$
u = sum_(j = 1)^r u_j "mit" u_j = 0, j != i "und" u_j = u, j = i
$
Dann gilt $u in U_i$ und insbesondere $u in U_1 + ... + U_(i-1) + U_(i+1) + ... U_r$. Somit ist die Schnittmenge $U_i sect U_1 + ... + U_(i-1) + U_(i+1) + ... + U_r != {0_V}$.
#endproof
#definition("3.36", "Direkte Summe")[
Sei $V$ ein $K$-VR und $r in NN, U_1, ..., U_r$ Untervektorräume von $V$. Dann heißt die Summe $sum U_i$ #bold[direkt], falls eine der Bedingungen aus Lemma 3.35 zutrifft.
Wir schreiben dann
$
U_1 oplus U_2 oplus ... oplus U_r
$
] <def>
#bold[Beispiel 3.37:] Seien $V, U_1, U_2$ wie im Beispeil 3.34. Dann gilt $V = U_1 + U_2$, aber nicht $U_1 oplus U_2$. Sei weiter $U_3 := "Span"{(0, 0, 1)}$. Dann gilt $V = U_1 + U_3$ und $U_1 oplus U_3$.
#bold[Lemma] (ohne Nummer)
Sei $V$ ein $K$-VR. Seien $U_1, U_2$ UVRs von $V$. Dann gilt
$
dim(U_1 + U_2) <= dim U_1 + dim U_2 space (ast)
$
Falls $U_1 oplus U_2$, gilt sogar Gleichheit.
Dabei sei $infinity + infinity = infinity, infinity + n = infinity, n <= infinity "für" n in NN$ und es gilt $infinity <= infinity$.
#italic[Beweis:]
#bold[Fall 1:] $dim U_1 = infinity$ oder $dim U_2 = infinity$. Dann gilt $(ast)$ nach den Rechenregeln der erweiterten Arithmetik.
#bold[Fall 2:] Andernfalls existieren $m, l in NN$ mit $dim U_1 = m "und" dim U_2 = l$.
Sei $u_1, ..., u_m$ eine Basis von $U_1$ und $u_(m+1), ..., u_(m+l)$ eine Basis von $U_2$. Sei weiter $u in U_1 + U_2$, dann existieren $v in U_1$ und $w in U_2$, sodass $u = v + w$. Zu $v$ und $w$ existieren $lambda_1, ..., lambda_m in K$ bzw. $lambda_(m+1), ..., lambda_(m+l) in K$ mit
$
v = sum_(i = 1)^m lambda_i u_i "und" w = sum_(i = m + 1)^(m+l) lambda_i u_i
$
Also $u = v + w$
$
u = sum_(i = 1)^m lambda_i u_i + sum_(i = m +1)^(m+l) lambda_i u_i = sum_(i = 1)^(m+l) lambda_i u_i
$
Also ist $u_1, ..., u_(m+l)$ ein Erzeugendensystem von $U_1 + U_2$. Es folgt $dim(U_1 + U_2) <= m+l = dim U_1 + dim U_2$.
Sei nun $U_1 oplus U_2$. Falls $dim(U_1 + U_2) = infinity$ gilt $(ast)$ mit Gleichheit. Andernfalls existieren $n in NN$ mit $dim(U_1 + U_2) = n$. Da $U_1$ und $U_2$ Untervektorräume von $U_1 + U_2$ sind, existieren $m, l in NN$ mit $dim U_1 = m <= n$ und $dim U_2 = l <= n$. Sei wieder $u_1, ..., u_m$ eine Basis von $U_1$ und $u_(m+1), ..., u_(m+l)$ eine Basis von $U_2$. Seien $lambda_1, ..., lambda_(m+l) in K$ mit
$
0 = sum_(i = 1)^(m+l) lambda_i u_i = underbrace(sum_(i = 1)^m lambda_i u_i, = space.sixth v space.sixth in space.sixth U_1) + underbrace(sum_(i = m+1)^(m+l) lambda_i u_i, = space.sixth w space.sixth in space.sixth U_2)
$
Da $U_1 oplus U_2$ folgt $v = 0 = w$. Da $u_i, i in {1, ..., m}$ eine Basis von $U_1$ ist, folgt $0 = lambda_i i in {1, ..., m}$. Analog folgt dies für $lambda_(m+1), ..., lambda_(m+l)$. Also ist $u_1, ..., u_(m+l)$ linear unabhängig.
$==>$ $dim U_1 + dim U_2 = m + l <= dim(U_1 + U_2)$
#endproof
#bold[Satz 3.38:] Sei $V$ ein $K$-VR und $U$ ein UVR von $V$. Dann existiert ein Untervektorraum $U^top subset.eq V$ mit $V = U oplus U^top$ (heißt $V = U + U^top$ und $U oplus U^top$). Insbesondere gilt dann
$
dim V = dim U + dim U^top
$
#italic[Beweis:] Sei $(u_i)_(i in I)$ eine Basis von $U$. Nach Satz 3.21 existiert eine Menge $J$ und Vektoren $w_j, j in J$ mit
$
I sect J = emptyset "und" v_k := cases(u_k &k in I, w_k &k in J) wide k in I union J
$
ist eine Basis von $V$.
Mit $U^top = "Span"{w_j}_(j in J)$ gilt dann $V = U + U^top$. Sei $v in V$, dann existieren eindeutige ${lambda_i}_(i in I) subset.eq K$ mit
$
v = sum_(k in I union J) lambda_k v_k = underbrace(sum_(k in I) lambda_k v_k, in space.sixth U) + underbrace(sum_(k in J) lambda_k v_k, in space.sixth U^top)
$
die Eindeutigkeit der $lambda_k, k in I union J$ garantiert die Eindeutigkeit von $u$ und $w$. Also $U oplus U^top$.
#endproof
Ein durch Satz 3.38 aus $U$ und $V$ erhaltener Untervektorraum $U^top$ heißt #bold[Komplement] von $U$ in $V$.
#bold[Beispiel 3.39:] Seien $V, U_1$ und $U_3$ wie in Beispiel 3.37. Dann gilt $V = U_1 oplus U_3$ d.h. $U_3$ ist ein Komplement von $U_1$ in $V$. Sei weiter $tilde(U_3) := "Span"{(1, 0, 1)}$. Dann gilt auch $V = U_1 oplus tilde(U_3)$.
Insbesondere sind die Komplemente aus Satz 3.38 nicht eindeutig bestimmt.
#bold[Satz 3.40:] Sei $V$ ein endlich erzeugter $K$-VR. Seien $U_1, U_2$ UVRs von $V$. Dann gilt
$
dim(U_1 sect U_2) + dim(U_1 + U_2) = dim U_1 + dim U_2
$
#italic[Beweis:] Sei $U := U_1 sect U_2$ und für $i in {1, 2}$ sei $W_i$ das Komplement von $U$ in $U_i$. Es gilt
$
U_i = U oplus W_i, space i in{1, 2}
$
Dann gilt $U_1 + U_2 = U + W_1 + U + W_2 = U + W_1 + W_2$
$
W_1 sect (U + W_2) &= W_1 sect W_2 \
&= W_1 sect U_1 sect U_2 ("da" W_1 subset.eq U_1) \
&= W_1 sect U \
&= {0_V}
$
Analog folgt $W_2 sect (U + W_1) = {0_V}$. Sei $u in U_1, w_1 in W_1, w_2 in W_2$ mit $0 = u + w_1 + w_2$, dann gilt
$
w_1 = - (u + w_2) \
w_2 = - (u + w_1)
$
Also $w_1 = 0$ und $w_2 = 0$ und damit auch $u = 0$. Also $U oplus W_1 oplus W_2$. Es folgt
$
dim(U_1 + U_2) &= dim(U + W_1) + dim W_2 \
&= dim U + dim W_1 + dim W_2
$
Aus der Wahl von $W_i$ folgt
$
dim U_1 = dim U + dim W_1 \
dim U_2 = dim U + dim W_2
$
durch Einsetzen erhält man
$
dim U + dim(U_1 + U_2) = dim U_1 + dim U_2
$
oder (nur für endliche wegen $- infinity$)
$
dim(U_1 + U_2) = dim U_1 + dim U_2 - dim U
$
#endproof
#pagebreak()
= Lineare Abbildungen
Nun behandeln wir Abbildungen, die zur Vektorstruktur "passen". Diese heißen lineare Abbildungen. Unser Ziel ist es, die Eigenschaften von linearen Abbildungen zu analysieren.
== Definitionen und grundlegende Eigenschaften
#definition("4.1", "Lineare Abbildung")[
Seien $V$ und $W$ zwei $K$-Vektorräume. Eine Abbildung $f: V -> W$ heißt #bold[lineare Abbildung], wenn gilt
#box(width: 100%, inset: (left: 0.5cm, right: 0.5cm))[
1. $underbrace(f(lambda dot v), "Skalarmultiplikation in" V) = underbrace(lambda dot f(v), "Skalarmultiplikation in" W) wide forall space.sixth v in V, forall space.sixth lambda in K$
#h(5pt)
2. $underbrace(f(v + w), "Addition in" V) = underbrace(f(v) + f(w), "Addition in" W) wide forall space.sixth v,w in V$
#h(5pt)
]
Die Menge aller linearen Abbildungen von $V$ nach $W$ bezeichnet man mit $L(V, W)$. Eine lineare Abbildung $f: V -> W$ wird auch #bold[lineare Transformation] oder #bold[(Vektorraum-) Homomorphismus] genannt.
Eine bijektive lineare Abbildung nennt man #bold[(Vektorraum-) Isomorphismus]. Gibt es für zwei $K$-Vektorräume $V$ und $W$ einen Isomorphismus, so heißen die Räume $V$ und $W$ isomorph, geschrieben
$
V isomorph W
$
Eine lineare Abbildung $f: V -> V$ heißt #bold[Endomorphismus] und ein bijektiver Endomorphismus heißt #bold[Automorphismus].
] <def>
#bold[Bemerkung:] Als Übungsaufgabe:
$
"Definition 4.1, 1) + 2)" <==> f(lambda v + mu w) = lambda f(v) + mu f(w) wide forall v, w in V, forall lambda, mu in K
$
#bold[Beispiel 4.2:] Für $a in RR$ ist $f: RR -> RR, f(x) = a x$ eine lineare Abbildung. Ihr Graph ist eine Gerade durch den Ursprung.
Betrachte eine Gerade $f(x) = a x + b$ und betrachte
$
&f(x + y) = a(x + y) + b \
&f(x) + f(y) = a(x) + b + a(y) + b = a(x+y) + 2b
$
$f$ ist also nur eine lineare Abbildung, wenn $b = 0$ gilt. Streng genommen sind Geraden der Form $f(x) = m x + n$ keine linearen Abbildung. Korrekt ist, sie als affine Abbildungen zu bezeichnen.
#bold[Beispiel 4.3:] Für $a, b, c, d in RR$ ist $f: RR^2 -> RR^2$
$
f(vec(x_1, x_2)) = vec(a x_1 + b x_2, c x_1 + d x_2) in RR^2
$
eine lineare Abbildung, denn
1)
$
f(lambda vec(x_1, x_2)) &= vec(a lambda x_1 + b lambda x_2, c lambda x_1 + d lambda x_2) = vec(lambda(a x_1 + b x_2), lambda (b x_1 + c x_2)) \
&= lambda vec(a x_1 + b x_2, c x_1 + d x_2) = lambda f(vec(x_1, x_2)) space checkmark
$
2)
$
f(vec(x_1, x_2) + vec(y_1, y_2)) &= f(vec(x_1 + y_1, x_2 + y_2)) = vec(a(x_1 + y_1) + b(x_2 + y_2), c(x_1 + y_1) + d(x_2 + y_2)) \
&= vec(a x_1 + b x_2, c x_1 + d x_2) + vec(a y_1 + b y_2, c y_1 + d y_2) = f(vec(x_1, x_2)) + f(vec(y_1, y_2))
$
Damit haben wir auch bewiesen, dass für $phi in RR$ die Abbildung
$
f(vec(x_1, x_2)) = vec(cos(phi) x_1 - sin(phi) x_2, sin(phi) x_1 + cos(phi) x_2)
$
linear ist. Dies ist eine Drehung um den Ursprung mit dem Drehwinkel $phi$. Für $phi = 45°$
$
f(vec(1,0)) = (cos(45°), sin(45°)) = vec(1/sqrt(2), 1/sqrt(2))
$
#bold[Beispiel 4.4:] Sei $V = C^infinity (RR)$ der reelle Vektorraum aller unendlich oft differenzierbaren Funktionen $g: RR -> RR$ mit punktweisen Addition und skalaren Multiplikation. Dann ist
$
d/(d x): V -> V, f arrow.bar f' = d/(d x) f
$
eine lineare Abbildung, denn für alle $f, g in V$ und $a, b in RR$ gilt:
$
(f + g)'(x) = f'(x) + g'(x) wide forall x in RR \
(a dot f)'(x) = a f'(x) wide forall x in RR
$
#bold[Lemma 4.5:] Seien $V, W$ $K$-Vektorräume und $f: V -> W$ eine lineare Abbildung, $0_V$ der Nullvektor in $V$ und $0_W$ der Nullvektor in $W$. Dann gilt
#box(width: 100%, inset: (left: 1cm, right: 1cm))[
1. $f(0_V) = 0_W$
2. $f(-x) = -f(x) wide forall x in V$
]
#italic[Beweis:] Es folgt aus Definition 4.1, 1), dass
$
f(0_V) = f(0_K dot 0_V) = 0_K dot f(0_V) = 0_W \
f(-x) = f((-1) dot x) = (-1) dot f(x) = -f(x)
$
#endproof
#bold[Lemma 4.6:] Seien $V, W$ $K$-Vektorräume. Für $f, g in L(V, W)$ und $lambda in K$ seien $f + g$ und $lambda dot f$ definiert durch
$
(f + g)(v) = f(v) + g(v) wide forall v in V \
(lambda dot f)(v) = lambda f(v) wide forall v in V, forall lambda in K
$
Dann ist $(L(V, W), +, dot)$ ein $K$-Vektorraum.
#italic[Beweis:] (Übungsaufgabe)
#endproof
#bold[Lemma 4.7:] Sei $V$ ein $K$-Vektorraum und $B := {v_1, ..., v_n} subset V$ eine endliche Familie von Vektoren. Dann ist:
$
Phi_B: K^n -> V, (a_i)_(1 <= i <= n) arrow.bar sum_(i = 1)^n a_i v_i
$
ein Homomorphimus von $K$-Vektorräumen.
#italic[Beweis:] Seien $lambda in K$ und zwei Tupel $a = (a_1, ..., a_n) in K^n$, $b = (b_1, ..., b_n) in K^n$ gegeben. Mit der Definition der direkten Summe ist.
$
a + lambda b = (a_i + lambda b_i)_(1<=i<=n) in K^n
$
und deswegen gilt
$
Phi_B (a + lambda b) &= Phi_B (a_i + lambda b_i)_(1 <= i <= n) = sum_(i = 1)^n underbrace((a_i + lambda b_i), in space.sixth K) underbrace(v_i, in space.sixth V) \
&= sum_(i = 1)^n a_i v_i + lambda sum_(i = 1)^n b_i v_i = Phi_B (a) + lambda Phi_B (b) = "Def 4.1"
$
#endproof
#bold[Wichtig:] $B = {v_1, ..., v_n}$ ist endlich! Für $B$ mit unendlich vielen Elementen bräuchte man eine äußere direkte Summe.
Aus abstrakter Sicht kennen wir jetzt endlichdimensionale Vektorräume, denn: Jeder endlichdimensionaler Vektorraum ist isomorph zu einer direkten Summe von Kopien des Grundkörpers.
#bold[Satz 4.8:] Struktursatz für Vektorräume
Sei $V$ ein $K$-Vektorraum und $B = {v_1, ..., v_n} subset V$ eine Basis von $V$. Dann ist die Abbildung
$
Phi_B: K^n -> V, (lambda_i)_(1 <=i <= n) arrow.bar sum_(i = 1)^n lambda_i v_i
$
ein Isomorphismus, d.h. $K^n isomorph V$.
#italic[Beweis:] Nach Lemma 4.7 ist $Phi_B$ eine lineare Abbildung. Zu zeigen: $Phi_B$ ist bijektiv
$
B "Basis" ==> "Span" B = V ==> Phi_B "surjektiv" \
B "Basis" ==> "jedes" v in V "besitzt eine eindeutige Darstellung" v = sum_(i = 1)^n lambda_i v_i
$
#endproof
Für eine gegebene Basis $B$ nenn man $Phi_B$ auch Koordinatenabbildung.
$
Phi "bijektiv" ==> exists Phi^(-1)_B "als inverse Abbildung"
$
#bold[Beispiel 4.9:] Sei $K^(n+1) = RR^(n+1)$ und $P_(<=n)[t]$ der Raum der Polynome von Grad kleiner gleich $n$ für $n in NN$. Eine Basis von $P_(<=n)[t]$ ist gegeben durch $B = {1, t, t^2, ..., t^n}$, vergleiche Beispiel 3.13.
Dann ist:
$
Phi_B: K^(n+1) -> P_(<=n)[t], space (a_i)_(0 <= i <= n) arrow.bar sum_(i = 0)^n a_i t^i
$
ein Isomorphismus. Weitherhin ist
$
Phi_B^(-1) = P_(<=n)[t] -> K^(n+1), space p(t) = sum_(i = 0)^n a_i t^i arrow.bar (a_i)_(0 <=i <= n) in K^(n+1)
$
die inverse Koordinatenabbildung.
Um eine lineare Abbildung zu definieren, reicht es ihre Werte auf einer beliebigen Basis anzugeben.
#bold[Lemma 4.10:] Sei $V$ ein endlichdimensionaler Vektorraum über $K$ mit einer Basis $B := {v_1, .., v_n}$, $W$ ein beliebiger $K$-Vektorraum und $C = {w_1, ..., w_n}$ eine Familie von Vektoren in $W$. Dann gibt es genau eine lineare Abbildung $f$ von $V$ nach $W$ mit
$
f(v_i) = w_i "für" 1 <= i <=n
$
#italic[Beweis:] zu zeigen: Existenz und Eindeutigkeit
Eindeutigkeit: Seien $f, g in L(V, W)$ mit $f(v_i) = g(v_i) = w_i$, $forall i in {1, ..., n}$. Sei $v in sum lambda_i v_i$: Dann gilt
$
f(v) &= f(sum lambda_i v_i) = sum_(i = 1)^n lambda_i f(v_i) \
&= sum_(i = 1)^n lambda_i w_i = sum_(i = 1)^n lambda_i g(v_i) = g(v) \
&==> f(v) = g(v) space forall v in V \
&==> f "ist eindeutig bestimmt"
$
Existenz: $B$ Basis $==> "Span" B = V ==> "zu" v in V$ existieren nach Satz 3.8 eindeutige Koordinaten
$
lambda_i^v, 1<=i<=n "mit"
v = sum_(i = 1)^n lambda_i^v v_i
$
Definiere $f: V -> W, space f(v) = sum_(i = 1)^n lambda_i^v w_i in W ==> f(v_i) = w_i$
Ist $f$ linear?
Für jedes $mu in K$ gilt:
$
mu v &= sum_(i = 1)^n (mu lambda_i^v v_i) ==> f(mu v) = f(sum_(i = 1)^n (mu lambda_i^v v_i)) =^"Def" sum_(i = 1)^n (mu lambda_i w_i) \
&= mu sum_(i = 1)^n lambda_i^v w_i = mu f(v) wide "erste Eigenschaft" checkmark
$
Sei $u = sum_(i = 1)^n lambda_i^u v_i ==>$
$
f(v + u) &= f(sum_(i = 1)^n lambda_i^v v_i + sum_(i = 1)^n lambda_i^u v_i) = f(sum_(i = 1)^n (lambda_i^v + lambda_i^u) v_i) \
&= sum_(i = 1)^n (lambda_i^v + lambda_i^u) w_i = sum_(i = 1)^n lambda_i^v w_i + sum_(i = 1)^n lambda_i^u w_i \
&= f(v) + f(w) wide "zweite Eigenschaft" checkmark
$
$
==> f "linear"
$
#endproof
== Kern, Bild und Rang von linearen Abbildungen
Kern und Bild wurden bereits im Kapitel 2 behandelt. Hier behandeln wir die Konzepte im Kontext linearer Abbildungen.
#definition("4.11", "Kern, Bild")[
Es seien $V$ und $W$ $K$-Vektorräume sowie $f: V -> W$ eine lineare Abbildung. Die Menge
$
ker(f) := {v in V | f(v) = 0}
$
heißt #bold[Kern] der linearen Abbildung $f$.
Die Menge
$
im(f) := f(V) = {w in W | exists v in V: w = f(v)}
$
heißt #bold[Bild] der linearen Abbildung $f$.
] <def>
#bold[Beispiel 4.12:]
#box(width: 100%, inset: (right: 1cm, left: 1cm))[
1. #[Für den Isomorphismus aus Beispiel 4.9 gilt:
$
Phi_B: K^(n+1) -> P_(<=n)[t]
$
mit
$
ker(Phi_B) = {0_(K^(n+1))}
$
denn nur $0 in K^(n+1)$ wird auf das Nullpolynom abgebildet.
]
2. #[
Fortsetzung von Beispiel 4.3 (Drehungsmatrizen)
Für $a = 0 = b$, $c, d in RR, c != 0$ und damit
$
f: RR^2 -> RR^2, space f(vec(x_1, x_2)) = vec(a x_1 + b x_2, c x_1 + d x_2) = vec(0, c x_1 + d x_2)
$
gilt:
$
ker(f) = {vec(x_1, x_2) in RR^2 | x_1 = -(d x_2) / c}, \
im(f) = {vec(0, x) | x in RR} subset RR^2
$
weil $x = c x_1 + d x_2$ für jedes $x in RR$ lösbar ist $(c != 0)$.
]
]
#bold[Lemma 4.13:] Es seien $V$ und $W$ zwei $K$-Vektorräume und $f: V -> W$ eine lineare Abbildung. Dann gilt :
#box(width: 100%, inset: (left: 1cm, right: 1cm))[
1. $ker(f) subset.eq V$ ist ein Untervektorraum von $V$
2. $im(f) subset.eq W$ ist ein Untervektorraum von $W$
]
#italic[Beweis:]
zu 1) $0_V in ker(f) ==> ker(f) != emptyset$. Weitherhin ist $ker(f)$ abgeschlossen bezüglich der Addition und Multiplikation, denn sei $x, tilde(x) in ker(f), lambda, mu in K$.
Zu zeigen: $lambda x + mu tilde(x) in ker(f)$
$
f(lambda x + mu tilde(x)) = lambda f(x) + mu f(tilde(x)) = 0_W \
==> "Abgeschlossenheit in" V
$
Daraus folgt auch mit $tilde(x) = 0_V$ die Abgeschlossenheit bezüglich der Multiplikation.
$==> ker(f)$ Unterraum $checkmark$
zu 2) $f(0_V) = 0_W in im(f) != emptyset$
zu zeigen: $im(f)$ abgeschlossen bezüglich $+$ und $dot$. Seien $y, tilde(y) in im(f), lambda, mu in K$
$==> x, tilde(x) in V: f(x) = y and f(tilde(x)) = tilde(y)$. Dann gilt für $lambda x + mu tilde(x)$, dass
$
f(lambda x+ mu tilde(x)) &= lambda f(x) + mu f(tilde(x)) = lambda y + mu tilde(y) \
&==> lambda x + mu tilde(x) "ist das Urbild von" lambda y + mu tilde(y) \
&==> lambda y + mu tilde(y) in im(f)
$
#endproof
#definition("4.14", "Rang einer Abbildung")[
Es seien $V$ und $W$ zwei $K$-Vektoräume und $f: V -> W$ eine lineare Abbildung. Der #bold[Rang] der linearen Abbildung $f$ ist definiert als
$
rg(f) := dim_K (im(f))
$
] <def>
#bold[Lemma 4.15:] Es seien $V$ und $W$ zwei $K$-Vektorräume und $f in L(V, W)$, $W$ sei endlichdimensional. Dann gilt
#box(width: 100%, inset: (left: 1cm, right: 1cm))[
1. $f$ surjektiv $<==>$ $rg(f) = dim W$
2. $f$ injektiv $<==>$ $dim(ker(f)) = 0$
]
#italic[Beweis:]
zu 1) "$==>$": Sei $f$ surjektiv. Dann gilt $W = f(V) = im(f)$ und damit auch
$
rg(f) = dim(im(f)) = dim W
$
"$<==$": Es gilt $rg(f) = dim(im(f)) = W$. Nach Lemma 4.13 ist $im(f)$ ein Vektorraum. Da $W$ endlichdimensional ist, folgt mit Lemma 3.31
$
==> im(f) = W, space f "surjektiv"
$
zu 2) "$==>$": Sei $f$ injektiv. Wir wissen $f(0_V) = 0_W$.
$
==> ker(f) = {v in V | f(v) = 0} = {0_V} ==> dim(ker(f)) = 0
$
"$<==$": Es gilt $dim(ker(f)) = 0 ==> ker(f) = {0_V}$. Damit erhält man für $x, tilde(x) in V$ wegen der Linearität in $f$:
$
f(x) = f(tilde(x)) <==> f(x) - f(tilde(x)) = 0 <==> f(x - tilde(x)) = 0 in ker(f) \
<==> x - tilde(x) in ker(f) <==> x - tilde(x) = 0 <==> x = tilde(x) space f "injektiv"
$
#endproof
#bold[Satz 4.16:] Dimensionsformel
Seien $V$ und $W$ zwei endlichdimensionale $K$-Vektorräume und $f in L(V, W)$. Dann gilt
$
dim(ker(f)) + dim(im(f)) = dim V
$
#italic[Beweis:] Mit $r := dim(ker(f)), n := dim V$ gilt
$
v < infinity "und" r < infinity "sowie" r <= n
$
Sei $tilde(B) := {v_1, ..., v_r}$ eine Basis von $ker(f)$. Mithilfe des Austauschsatzes von Steinitz (3.23) kann $tilde(B)$ zu einer Basis $B = {v_1, ..., v_r, v_(r+1), ..., v_n}$ von $V$ ergänzt werden.
zu zeigen: $C = {f(v_(r +1 )), ..., f(v_n)}$ ist eine Basis von $im(f)$.
1) Erzeugendensystem
$f$ linear $==>$ $"Span" C subset im(f)$. Sei $y in im(f) ==> exists x in V: f(x) = y$.
$B$ ist eine Basis von $V$ $==>$ es existiert eine eindeutige Darstellung
$
x = sum_(i = 1)^n lambda_i v_i
$
Mit der Linearität von $f$ folgt:
$
f(x) = f(sum_(i = 1)^n lambda_i v_i) = sum_(i = 1)^n lambda_i f(v_i) = y \
v_1, ..., v_r in ker(f) ==> y = f(x) = sum_(i = r+1)^n lambda_i f(v_i) \
==> im(f) subset.eq "Span" C \
==> im(f) = "Span" C \
checkmark
$
lineare Unabhängigkeit: Sei
$
sum_(i = r+1)^n lambda_i f(v_i) = 0
$
zu zeigen: $x_i = 0 "für" r + 1 <= i <= n$
$
f "linear" ==> 0 = sum_(i = r +1)^n lambda_i f(v_i) = f(sum_(i = r+1)^n lambda_i v_i) \
==> sum_(i = r+1)^n lambda_i v_i in ker(f)
$
$==>$ es existieren eindeutige Koeffizienten $mu_i in K, 1 <= i <= r$
$
sum_(i = r+1)^n lambda_i v_i = sum_(i = 1)^r mu_i v_i
==> sum_(i = r+1)^n lambda_i v_i - sum_(i = 1)^r mu_i v_i = 0
$
${v_1, ..., v_n}$ sind Basis von $V$. $==>$ $mu_1 = ... = mu_r = lambda_(r+1) = ... = lambda_n = 0$. $==>$ $f(v_(r+1)), ..., f(v_n)$ sind linear unabhängig $==>$ $C$ ist Basis von $im(f)$
$
==> dim(im(f)) = n - r
$
#endproof
#bold[Beispiel 4.17:] Fortsetzung von Beispiel 4.12.
zu 1)
#box(width: 100%, inset: (left: 1cm, right: 1cm))[
$Phi_B: K^(n+1) -> P_(<=n)[t]$
Es gilt $ker(Phi_B) = {0} ==> dim(ker(f)) = 0$
$==> dim(P_(<=n)[t]) = n + 1$
]
zu 2)
#box(width: 100%, inset: (left: 1cm, right: 1cm))[
$f: RR^2 -> RR^2, space a = b = 0, c != 0, c, d in RR$
Es gilt
$
dim(ker(f)) = dim({vec(x_1, x_2) | x_1 = (d x_2)/c}) &= 1 \
dim(im(f)) = dim({vec(0, x) | x in RR}) &= 1 \
dim(ker(f)) + dim(im(f)) = dim(RR^2) &= 2
$
]
#bold[Beispiel 4.18:] Sei $V = RR^3, W = RR^3$ und $f: V -> W$
$
f(vec(x_1, x_2, x_3)) = vec(x_1 - x_2 + 2 x_3, x_1 + x_2 + x_3, 0x_1 + 3x_2 + 0x_3)
$
gegeben. Damit ist $f$ linear. Nach Lemma 4.10 wird das Bild $im(f)$ durch die Bilder $f(e_1), f(e_2)$ und $f(e_3)$ erzeugt.
$
==> im(f) = "Span"{vec(1,1,0), vec(-1, 1, 3), vec(2,2,0)} \
==> rg(f) = dim(im(f)) = 2
$
Aus der Dimensionsformel folgt
$
dim(ker(f)) = dim(V) - dim(im(f)) = 3 - 2 = 1 \
==> {0_(RR^3)} subset ker(f)
$
#bold[Lemma 4.19:] Zwei endlichdimensionale $K$-Vektorräume $V$ und $W$ sind genau dann isomorph, wenn
$
dim(V) = dim(W)
$
#italic[Beweis:]
"$==>$": Gilt $V isomorph W$, so existiert ein Isomorphismus $f in L(V, W)$.
Lemma 4.15:
$
ker(f) = {0} wide (f "injektiv") \
im(f) = W wide (f "surjektiv")
$
Satz 4.16:
$
dim(V) &= dim(ker(f)) + dim(im(f)) \
&= 0 + dim(W) \
&= dim(W) space checkmark
$
"$<==$": $dim(V) = dim(W) < infinity$
Seien ${v_1, ..., v_n}$ und ${w_1, ..., w_n}$ Basen von $V$ bzw. $W$. Nach Lemma 4.10 gibt es genau eine Abbildung $f in L(V, W)$ mit
$
f(v_i) = w_i, wide 1 <= i <= n
$
Ist $v = lambda_1 v_1 + lambda_2 v_2 + ... + lambda_n v_n in ker(f)$. Dann gilt\
$ 0 = f(v) &= f(lambda_1 v_1 + ... + lambda_n v_n)\
& #h(-17pt) attach(=, t: f in L(V, W)) lambda_1 f(v_1) + ... + lambda_n f(v_n)\
&= lambda_1 w_1 + ... + lambda_n w_n
$
$w_1, ..., w_n$ linear unabhängig\
$==>$ $lambda_1 = lambda_2 = ... = lambda_n = 0 ==> v = 0 ==> ker(f) = {0_V} attach(==>, t: "4.15") f "injektiv"$.\
Mit der Dimensionsformel folgt:
$
dim(W) = dim(V) &= 0 + dim(im(f))
$
$
==> "mit" im(f) subset.eq W ==> im(f) = W ==> f "surjektiv"
$
#endproof
Was passiert bei Verknüpfungen von linearen Abbildungen?
#bold[Satz 4.20:] Seien $V, W$ und $X$ drei endlichdimensionale $K$-Vektorräume sowie $f in L(V, W)$ und $g in L(W, X)$. Dann gilt
$
g circ f in L(V, X) "und" \
dim(im(g circ f)) = dim(im(f)) - dim(im(f) sect ker(g))
$
#italic[Beweis:] 1) $g circ f in L(V, X)$: Für $u, v in V$ und $lambda, mu in K$ erhält man:
$
(g circ f)(lambda u + mu v) &= g(f(lambda u + mu v)) \
&= g(lambda f(u) + mu f(u)) = lambda g(f(u)) + lambda g(f(v)) \
&= lambda (g circ f)(u) + mu (g circ f)(v) space checkmark
$
2) Betrachte $tilde(g) = g_(|im(f))$. Die Dimensionsformel liefert
$
dim(im(f)) = dim(im(tilde(g))) + dim(ker(tilde(g)))
$
Des Weiteren gilt: $im(tilde(g)) := {g(v) in X | v in im(f)} = im(g circ f)$
$
ker(tilde(g)) = {v in im(f) | tilde(g)(v) = 0} = im(f) sect ker(g)
$
#endproof
#bold[Lemma 4.21:] Sei $K$ ein Körper. Die linearen Abbildungen $f: K^n -> K^m$ sind genau die Abbildungen der Form:
$
vec(x_1, x_2, dots.v, x_n) -> vec(a_(1 1) x_1 + a_(1 2) x_2 + ... + a_(1 n) x_n, a_(2 1) x_1 + a_(2 2) x_2 + ... + a_(2 n) x_n, dots.v, a_(m 1) x_1 + a_(m 2) x_2 + ... + a_(m n) x_n)
$
mit Koeffizienten $a_(i j) in K$ für $1 <= i <= m$ und $1 <= j <= n$.
#italic[Beweis:] "$<==$": Die Dimensionen passen aufgrund der Definitionen. Die Linearität $f$ folgt aus den Rechengesetzen im Körper.
"$==>$": Sei $f in L(K^n, K^m)$. Zu zeigen: $f$ ist in angegebener Form darzustellen.
#bold[Beobachtung:] Wenn $f$ so darstellbar ist, haben alle Bilder der Standardbasis $e_1, ..., e_n$ folgende Form:
#v(-2pt)
$
f(e_i) = vec(a_(1 i), dots.v, a_(m i)) in K^m
$
#v(-2pt)
Deswegen definieren wir
#v(-2pt)
$
vec(a_(1 i), dots.v, a_(m i)) := f(e_i) in K^m
$
#v(-2pt)
Jetzt definieren wir $g in L(K^n, K^m)$ durch
#v(-2pt)
$
g(vec(x_1, dots.v, x_n)) = vec(a_(1 1) x_1 + ... + a_(1 n) x_n, dots.v, a_(m 1) x_1 + ... + a_(m n) x_n)
$
#v(-2pt)
Per Konstruktion gilt $f(e_i) = g(e_i)$.
Mit Lemma 4.10 folgt $f = g$.
#endproof
Dieses Resultat motiviert das nächste Kapitel:
#pagebreak()
= Matrizen
<NAME> (brit. Mathematiker, 1814 - 1897) erfand den Begriff der Matrix im Jahr 1850. Die im Folgenden definierte Matrixoperationen führte <NAME> (brit. Mathematiker, 1821 - 1895) im Jahr 1858 ein.
== Definitionen und Basisoperationen
Wir nehmen für dieses Kapitel an: $R$ ist ein Ring mit $1 != 0$.
#definition("5.1", "Matrix")[
Sei $(R, +, dot)$ ein kommutativer Ring mit Eins und seien $n, m in NN_0$. Ein rechteckiges Schema der Form
$
mat(
a_(1 1), a_(1 2), ..., a_(1 n);
dots.v, dots.v, dots.down, dots.v;
a_(m 1), a_(m 2), ..., a_(m n);;
)
$
mit $a_(i j) in R$ für $1 <= i <= m$ und $1 <= j <= n$ heißt #bold[(m $times$ n) Matrix] mit den Einträgen in $R$. Die Einträge nennt man auch Koeffizienten. Die Menge aller ($m times n$) Matrizen nennt man $R^(m times n)$.
] <def>
#bold[Bemerkungen:]
#boxedlist[
Rein formal erlaubt diese Definition $n = 0$ oder $m = 0$. Dann erhält man Matrizen der Form $0 times n$, $m times 0$ oder $0 times 0$.
Diese leeren Matrizen werden in manchen Beweisen aus technischen Gründen benötigt. In der Regel gilt aber $n, m >= 1$.
][
Die Nullmatrix in $R^(m times n)$ ist die Matrix, bei der alle Einträge gleich $0$ sind. Sie wird mit $0^(m times n)$ bezeichnet
][
Ist $m = n$, so nennt man $A in R^(m times n)$ quadratisch bzw. eine quadratische Matrix
][
Ist $A in R^(n times n)$ heißen die Einträge $a_(j j)$ für $1 <= j <= n$ #bold[Diagonaleinträge] von
$
A = mat(
a_(1 1), ..., ...;
dots.v, dots.down, dots.v;
..., ..., a_(n n);
)
$
]
#boxedlist[
Die Kronecker-Delta Funktion $delta_(i j)$ für $i in I$ und $j in J$, $I$ und $J$ sind Indexmengen, ist benannt nach Le<NAME> (1823 - 1891) und gegeben durch
$
delta_(i j) = cases(1 &i = j, 0 "sonst")
$
Damit definiert man die Einheitsmatrix $I_n in R^(n times n)$ durch
$
I_n := [delta_(i j)] = mat(
1, ..., 0;
dots.v, dots.down, dots.v;
0 ,..., 1;
)
$
Man verwendet $I$, wenn $n$ aus dem Kontext klar ist.
][
Die $i$-te Zeile von $A in R^(m times n)$ ist
$
(a_(i 1), ..., a_(i n)) in R^(1 times n) "für" i = 1, ..., m "ist ein Zeilenvektor"
$
Die $j$-te Spalte von $A in R^(m times n)$ ist
$
vec(a_(1 j), dots.v, a_(m j)) in R^(m times 1) "für" i = 1, ..., n "ist ein Spaltenvektor"
$
Diese sind selbst wieder Matrizen.
][
Sind $m_1, m_2, n_1, n_2 in NN_0$ und $A_(i j) in R^(m, n)$ für $i,j = 1,2$ gegeben, definieren diese eine sogenannte #bold[Blockmatrix] der Form
$
A = mat(
A_(1 1), A_(1 2);
A_(2 1), A_(2 2);
) in R^(m_1 + m_2, n_1 + n_2)
$
]
#bold[Beispiel 5.2:] Für
$
A = mat(
1, -2, 3;
-4, 5, 6;
) in ZZ^(2, 3)
space "und" space
B = mat(
-1, 0;
0, 1;
1, -1;
) in ZZ^(3,2)
$
ist $a_(2 3) = 6$, $(1, -2, 3) in ZZ^(1,3)$ die erste Zeile von $A$ und $b_(2 2) = 1$ und
$
vec(0,1,-1) in ZZ^(3,1)
$
die zweite Spalte von $B$. Keine dieser Matrizen ist quadratisch.
#definition("5.3", "Addition von Matrizen")[
Seien $A, B in R^(m, n)$ zwei Matrizen. Dann ist $C = A + B in R^(m,n)$ definiert durch
$
C := A + B = mat(
a_(1 1), ..., a_(1 n);
dots.v, dots.down, dots.v;
a_(m 1), ..., a_(m n);
) + mat(
b_(1 1), ..., b_(1 n);
dots.v, dots.down, dots.v;
b_(m 1), ..., b_(m n);
) = mat(
a_(1 1) + b_(1 1), ..., a_(1 n) + b_(1 n);
dots.v, dots.down, dots.v;
a_(m 1) + b_(m 1), ..., a_(m n) + b_(m n);
)
$
Die Addition in $R^(m,n)$ erfolgt also komponentenweise basierend auf der Addition in $R$.
] <def>
#bold[Achtung:] Die Addition ist nur für Matrizen gleicher Größe / Dimension definiert.
#definition("5.4", "Multiplikation einer Matrix mit einem Skalar")[
Sei $A in R^(m,n)$ eine Matrix und $lambda in R$. Dann ist $C = lambda dot A in R^(m,n)$ definiert durch
$
C = lambda A = lambda mat(
a_(1 1), ..., a_(1 n);
dots.v, dots.down, dots.v;
a_(m 1), ..., a_(m n);
) = mat(
lambda a_(1 1), ..., lambda a_(1 n);
dots.v, dots.down, dots.v;
lambda a_(m 1), ..., lambda a_(m n);
)
$
Die Multiplikation einer Matrix mit einem Skalar aus $R$ erfolgt komponentenweise basierend auf der Multiplikation in $R$.
] <def>
#definition("5.5", "Multiplikation von Matrizen")[
Seien $A in R^(m,n)$ und $B in R^(n, l)$ zwei Matrizen. Dann ist $C = A dot B in R^(m, l)$ definiert durch
$
C := A dot B = mat(c_(1 1), ..., c_(1 l); dots.v, dots.down, dots.v; c_(m 1), ..., c_(m l)) space "mit" space c_(i j) = sum_(k = 1)^n a_(i k) dot b_(k j)
$
für $i = 1, ..., m$ und $j = 1, ..., l$
] <def>
#bold[Bemerkung:] Um das Produkt $A dot B$ berechnen zu können #bold[muss] die Anzahl der Spalten von $A$ gleich der Anzahl von Zeilen in $B$ sein.
#bold[Merkregel:]
$
c_(i j) = i"-te Zeile von" A "mal" j"-t Spalte von" B
$
Oder Zeile "mal" Spalte. ("mal" $corres$ Skalarprodukt)
#bold[Beispiel 5.6:] Für die Matrizen
$
A = mat(1, -2, 3; -4, 5, 6) in ZZ^(2,3), space B = mat(-1, 0; 0, 1; 1, -1) in ZZ^(3,2) space "und" space C = mat(1, 2; 3, 4; 5, 6) in ZZ^(3, 2)
$
gilt:
$A + B$ geht nicht
$
B + C = mat(0, 2; 3, 5; 6, 5) in ZZ^(3,2) wide 3 dot A = mat(3, -6, 9; -12, 15, 18) in ZZ^(2,3)
$
$
A dot B = mat(2, -5; 10, -1) in ZZ^(2,2) wide B dot A = mat(-1, 2, -3; -4, 5, 6; 5, -7, -3) in ZZ^(3,3)
$
Also $A dot B$ und $B dot A$ sind für dieses Beispiele definiert, aber $A dot B != B dot A$. Damit ist die Multiplikation von Matrizen nicht kommutativ. Dies gilt auch für gleichgroße Matrizen:
$
D = mat(1, -2; -4, 5) in ZZ^(2,2) space, space E = mat(-1, 0; 0, 1) in ZZ^(2,2) ==>
$
$
D dot E = mat(-1, -2; 4, 5) space != space mat(-1, 2; -4, 5) = E dot D
$
#bold[Lemma 5.7:] Für $A, tilde(A) in R^(m,m) space B, tilde(B) in R^(m,l), space C in R^(l,k) "sowie" lambda, mu in R$ gelten
#boxedlist[
Assoziativgesetze, d.h. #sspace
$
A dot (B dot C) = (A dot B) dot C space "und" (lambda mu) dot A = lambda dot (mu dot A)
$
][
Distributivitätsgesetze , d.h.
$
(A + tilde(A)) dot B &= A dot B + tilde(A) dot B \
A dot (B + tilde(B)) &= A dot B + A dot tilde(B)\
(lambda + mu) dot A &= lambda dot A + mu dot A \
lambda dot (A + tilde(A)) &= lambda dot A + lambda dot tilde(A)\
lambda dot (A dot B) &= A dot (lambda dot B)
$
][
und mit
$
I_n = mat(1, ..., 0; dots.v, dots.down, dots.v; 0, ..., 1) in R^(n,n) "bzw." I_m in R^(m,m)
$
gilt
$
I_n dot A = A = A dot I_m
$
]
#italic[Beweis:] Nachrechnen
#endproof
#definition("5.8", "Transposition von Matrizen")[
Sei
$
A = mat(a_(1 1), ..., a_(1 n); dots.v, dots.down, dots.v; a_(m 1), ..., a_(m n)) in R^(m times n)
$
eine Matrix. Dann ist die zu $A$ #bold[transponierte] Matrix $A^top$ definiert durch
$
A^top := mat(a_(1 1), ..., a_(m 1); dots.v, dots.down, dots.v; a_(1 n), ..., a_(m n)) in R^(n times m)
$
] <def>
#bold[Beispiel 5.9:] Die zu
$
A = mat(1,-2,3;-4,5,6) in ZZ^(2,3)
$
transponierte Matrix ist
$
A^top = mat(1, -4; -2, 5; 3, 6) in ZZ^(3,2)
$
#bold[Lemma 5.10:] Für $A, tilde(A) in R^(m,n), space B in R^(n,l) "und" lambda in R$ gilt
#box(width: 100%, inset: (left: 1cm, right: 1cm))[
#show par: set block(spacing: 0.65em)
1. $(A^top)^top = A$
2. $(A + tilde(A))^top = A^top + tilde(A)^top$
3. $(lambda dot A)^top = lambda dot A^top$
4. $underbrace(underbrace((A dot B), in space R^(m,l))^top, in space R^(l,m)) = underbrace(underbrace(B^top, in space R^(l,n)) dot underbrace(A^top, in space R^(n,m)), in space R^(l,m))$
]
#italic[Beweis:] Nachrechnen.
#endproof
#bold[Zur Notation:]
$
R^n, space v in R^n, space v = vec(v_1, dots.v, v_n) in R^(n,1)
$
d.h. $v$ wird immer als Spaltenvektor interpretiert.
Für Zeilenvektor:
$
w in R^(1,n) "gilt" w^top in R^(n,1) isomorph R^n
$
#bold[Beobachtung:] Alle Operationen, die wir für Matrizen definiert haben, sind konsistent mit den Vektoroperationen, wenn diese im obigen Sinn als Matrizen interpretiert werden.
== Matrizengruppen und -ringe
#bold[Lemma 5.11:] Mit den angegebenen Rechenregeln gilt
#box(width: 100%, inset: (right: 1cm, left: 1cm))[
1. #[
$(R^(m, n), +)$ ist eine kommutative Gruppe mit dem neutralen Element $0 in R^(m, n)$, d.h. der Nullmatrix und dem zu $A in R^(m, n)$ inversen Element $-A = (-a_(i j)) in R^(m, n)$. Manschreibt statt $A + (-B) = A - B$.
]
2. #[
Ist $R$ ein Körper, so ist $R^(m, n)$ ein $R$-Vektorraum der Dimension $m dot n$.
]
]
#italic[Beweis:]
1) Folgt durch nachrechnen unter Ausnutzung der Eigenschaften von $R$.
2) Aufgrund der Rechenregeln ist $R^(m,n)$ abgeschlossen bezüglich
$
+: R^(m, n) times R^(m, n) -> R^(m,n) space "und" space dot.op: R times R^(m,n) -> R^(m,n)
$
Zur Dimension: $A in R^(m,n)$ kann dargestellt werden durch
$
a_(1 1) dot mat(1, 0, ..., 0; dots.v, dots.v, dots.v, dots.v; 0, 0, ..., 0) + a_(1 2) dot mat(0, 1, ..., 0; dots.v, dots.v, dots.v, dots.v; 0, 0, ..., 0) + ... + a_(m n) dot mat(0, 0, ..., 0; dots.v, dots.v, dots.v, dots.v; 0, 0, ..., 1) \
==> "Erzeugendensystem + linear unabhängig" ==> "Basis"
$
#endproof
Aufgrund der Eigenschaft 2 aus Lemma 5.10 ist die Transposition von Matrizen ein Homomorphismus (vlg. Definition 2.11) der Gruppen $(R^(m,n), +)$ und $(R^(n,m), +)$
#bold[Lemma 5.12:] Sei $n in NN$. Die Menge der quadratischen Matrizen $R^(n, n)$, d.h. $(R^(n,n), +, dot)$, ist ein Ring mit Eins, welche durch die Einheitsmatrix $I_n$ gegeben ist. Dieser Ring ist nur für $n = 1$ kommutativ.
#italic[Beweis:] Lemma 5.11: $(R^(n,n), +)$ ist eine kommutative Gruppe mit neutralem Element $0 in R^(n,n)$. Lemma 5.7: Assoziativität, Distributivitätsgesetze, Einselement $I_n$. $==>$ Ring mit $1$ $space.thin checkmark$
$n = 1$: Kommutativität folgt aus Eigenschaften von $R$. Für $n = 2$ gilt mit
$
A = mat(0,0;1,0) space "und" space B = mat(0,0;0,1), "dass" \
A dot B = mat(0,0;0,0) != mat(0,0;1,0) = B dot A
$
#endproof
Aus dem Beispiel im letzten Satz folgt auch, dass $A, B in R^(n,n)$ mit
#boxedlist[$A != 0 in R^(n,n)$, $B != 0 in R^(n,n)$][$A dot B = 0$]
existiert. Damit besitzt $R^(n,n)$ sogenannte nichttriviale Nullteiler. Mit $R = RR$ gilt dies auch wenn $R$ ein Körper ist.
Weitere wichtige Eigenschaft:
Invertierbarkeit bezüglich der Multiplikation!
#bold[Frage:] Gibt es für jede Matrix $A in R^(n,n)$ eine Matrix $A^(-1)$, so dass $A dot A^(-1) = I_n = A^(-1) dot A$? Wenn dies gilt, dann müsste $A^(-1)$ existieren, so dass für
$
A = mat(0,0;1,0) space "gilt" space A dot A^(-1) = I = A^(-1) dot A \
A dot A^(-1) = mat(0,0;1,0) dot mat(a,b;c,d) =^! mat(1,0;0,1)
$
Für das erste Element der Matrix folgt
$
0 dot a + 0 dot c = underbrace(0 != 1, "Ring mit" 0 != 1) space arrow.zigzag
$
#bold[Folgerung:] Nicht alle quadratischen Matrizen sind invertierbar.
#bold[Beispiel 5.13:] Die Matrix
$
A = mat(1,0;2,3) in ZZ^(2,2)
$
ist damit über $R = ZZ$ nicht invertierbar. Es gilt
$
mat(1,0;2,3) dot underbrace(mat(1,0;-2/3, 1/3), A^(-1) space.thin in space.thin QQ^(2,2)) = mat(1,0;0,1) = I_2
$
Ist $A in QQ^(2,2)$, dann ist $A$ invertierbar. Also: Invertierbarkeit hängt vom Ring $R$ ab!
#sect_delim
#bold[Lemma 5.14:] Sind $A, B in R^(n,n)$ zwei invertierbare Matrizen. D.h. es existieren $A^(-1), B^(-1) in R^(n,n)$ mit $A dot A^(-1) = I = A^(-1) dot A$ und $B dot B^(-1) = I = B^(-1) dot B$, so gilt:
#boxedlist[
$A dot B$ ist invertierbar und es ist $#sspace$
$
(A dot B)^(-1) = B^(-1) dot A^(-1)
$
][
$A^top$ ist invertierbar und es ist $(A^top)^(-1) = (A^(-1))^top = A^(-top)$
]
#italic[Beweis:]
1. Aussage: Folgt aus der allgemeinen Aussage für Ringe mit Eins im Satz 2.13.
2. Aussage: Regel 4 aus Lemma 5.10:
$
(A^(-1))^top dot A^top = (A dot A^(-1))^top = (I_n)^top = I_n = (A^top)^(-1) dot A^top
$
#endproof
#bold[Lemma 5.15:] Die Menge $"GL"_n (R) := {A in R^(n,n) | A "invertierbar"}$ bilden mit der Matrixmultiplikation eine Gruppe.
#italic[Beweis:] Lemma 5.14, 1. Aussage: Abgeschlossenheit bezüglich $dot$. Lemma 5.7: Assoziativität $+$ neutrale Element $I_n$. Mit $(A^(-1))^(-1) = A$ ist auch $A^(-1)$ invertierbar $==>$ $A^(-1) in "GL"_n (R)$.
#endproof
#italic[Hinweis:] $space.thin"GL"_n (R)$ = General linear Group
Matrixmultiplikation: $A in R^(m,n), v in R^(n, 1) = R^n$
$
mat(a_(1 1), ..., a_(1, n); dots.v, dots.down, dots.v; a_(m 1), ..., a_(m n)) dot vec(v_(1 1), dots.v, v_(n 1)) = A dot v
$
definiert damit auch die Matrix-Vektor-Multiplikation.
Diese Beobachtung motiviert:
== Matrizen und lineare Abbildungen
#bold[Beispiel 5.16:] Fortsetzung von Beispiel 4.3.
Die lineare Abbildung $f: RR^2 -> RR^2$,
$
y = f(x) = f(vec(x_1, x_2)) = vec(a x_1 + b x_2, c x_1 + d x_2)
$
mit $a, b, c, d in RR$ wird beschrieben duch
$
y = f(x) = underbrace(underbrace(mat(a, b; c, d), in space.thin R^(2,2)) dot underbrace(vec(x_1, x_2), in space.thin R^(2, 1)), in space.thin R^(2,1)) = A dot x space "mit" A = mat(a, b; c, d)
$
Die Kombination mit Lemma 4.21 liefert:
#bold[Satz 5.17:] Sei $K$ ein Körper. Zu jeder linearen Abbildung $f: K^n -> K^m, space.thin y = f(x)$, existiert eine Matrix $A in K^(m,n)$, so dass gilt
$
y = f(x) = A dot x
$
#italic[Beweis:] Nach Lemma 4.21 besitzt jede lineare Abbildung $f: K^n -> K^m$ die Form
$
y = f(x) = mat(a_(1 1) x_1 + a_(1 2) x_2 + ... + a_(1 n) x_n; a_(2 1) x_1 + a_(2 2) x_2 + ... + a_(2 n) x_n; dots.v; a_(m 1) x_1 + a_(m 2) x_2 + ... + a_(m n) x_n)
$
mit Koeffizienten $a_(i j) in K$, $i = 1, ..., m$, j = $1, ..., n$. Mit den Rechenregeln für Matrizen inklusive dem Spezialfall der Vektoren folgt
$
y = f(x) = A dot x space "mit" space A = mat(a_(1 1), a_(1 2), ..., a_(1 n); a_(2 1), a_(2 2), ..., a_(2 n); dots.v, dots.v, dots.v, dots.v; a_(m 1), a_(m 2), ..., a_(m n))
$
#endproof
Was gilt für allgemeine Basen?
#bold[Satz 5.18:] Seien $V$ und $W$ zwei $K$-Vektorräume mit den Basen $B = {v_1, ..., v_n}$ von $V$ und $C = {w_1, ..., w_m}$ von $W$ und $f: V -> W$ eine lineare Abbildung. Dann gibt es eine eindeutig bestimmte Matrix $A_f^(B, C) = (a_(i j)) in K^(m, n)$, so dass
$
W in.rev f(v_j) = sum_(i = 1)^m a_(i j) w_i wide j = 1, ..., n
$
gilt. Die Abbildung $F: L(V, W) -> K^(m, n)$ mit $F(f) = A_f^(B, C)$ ist ein Isomorphismus zwischen zwei $K$-Vektorräumen.
#italic[Beweis:] Da $C$ eine Basis von $W$ ist, besitzt jedes $w in W$ eine eindeutige Darstellung als Linearkombination der Vektoren ${w_1, ..., w_m}$. Damit besitzt auch für jedes $f in L(V, W)$ die Vektoren $f(v_1), ..., f(v_n)$ eine eindeutige Darstellung. Die Koeffizienten dieser Linearkombinationen bestimmen eindeutig die Matrix $A_f^(B, C)$.
zu zeigen: $F$ ist ein Isomorphismus.
$F$ ist linear: Seien $f, g in L(V, W)$ mit den zugehörigen Matrizen $A_f^(B, C)$ bzw. $A_g^(B, C)$ mit
$
A_f^(B, C) = (a_(i j)), A_g^(B, C) = (b_(i j)), A_f^(B, C) in K^(m, n), A_g^(B, C) in K^(m, n)
$
Für $lambda, mu in K$ gilt
$
(lambda f + mu g)(v_j) &= lambda f(v_j) + mu g(v_j) = lambda sum_(i = 1)^m a_(i j) w_i + mu sum_(i = 1)^m b_(i j) w_i \
&= sum_(i = 1)^m underbrace((lambda a_(i j) + mu b_(i j)), "Matrix für" lambda f + mu g) w_i
$
Also ist
$
F(lambda f + mu g) = lambda F(f) + mu F(g)
$
$==> F$ linear
noch zu zeigen: $F$ ist bijektiv
Sei $f in "ker"(F)$, dann $F(f) = 0 in K^(m,n)$. Also ist $f(v_j) = 0$ für $j = 1, ..., n$. Da ${v_1, ..., v_n}$ eine Basis von $V$ ist, folgt für alle $v in V:$
$
f(v) = f(sum_(j = 1)^n lambda_j v_j) attach(=, t: f "linear") sum_(j = 1)^n lambda_j underbrace(f(v_j), 0 in W) = 0 in W \
==> f = 0 in L(V, W) ==> "ker"(F) = {0} ==>^"Lemma 4.15" F "injektiv"
$
Sei $A in K^(m,n)$ beliebig gewählt. zu zeigen: $exists f in L(V, W): F(f) = A$.
Lemma 4.10: Es existiert genau eine lineare Abbildung $f in L(V,W)$ mit
#align(center, box(width: 80%, height: auto, inset: 0.5cm, radius: 10pt, fill: rgb(245, 245, 245), [
#set align(left)
#bold[Zwischenüberlegung]
#v(5pt)
${tilde(w)_1, ..., tilde(w)_n} space exists! f: f(v_j) = tilde(w)_j space space j = 1, ..., n$
$
==> tilde(w)_j = sum_(i = 1)^m a_(i j) w_i, space.quad j = 1, ..., n space "mit" space A = (a_(i j)) in K^(m,n)
$
]))
$
f(v_j) = sum_(i = 1)^m a_j w_i space j = 1, ..., n
$
Für diese $f$ gilt dann $F(f) = A$
$
==> F "surjektiv"
$
#endproof
#bold[Bemerkungen:]
#boxedlist[Im letzten Satz kann man #bold[nicht] $#sspace$
$
f(v_j) = w_j
$
fordern, da $n != m$ gelten kann.][
Wir hatten schon: $V$ $K$-Vektorraum, $"dim"(V) = n in NN$
$
"dann" V isomorph K^n
$
Mit Satz 5.18 folgt jetzt:
$
L(V, W) isomorph K^(n,m)
$
][
Aus Satz 4.19 und Lemma 5.11 mit dem Körper $K$ folgt
$
"dim"(L(V,W)) = "dim"(K^(m,n))
$
]
#definition("5.19", "Matrixdarstellung")[
Seien $V$ und $W$ zwei $K$-Vektorräume mit den Basen $B = {v_1, ..., v_n}$ von $V$ und $C = {w_1, ..., w_m}$ von $W$ sowie $f in L(V, W)$. Die durch Satz 5.18 eindeutig bestimmte Matrix $A_f^(B,C) in K^(m, n)$ heißt #bold[Matrixdarstellung] oder die #bold[darstellende Matrix] von $f in L(V, W)$ bezüglich der Basen $B$ und $C$.
] <def>
#bold[Beispiel 5.20:] Fortsetzung von Beispiel 4.3. Die lineare Abbildung $f: RR^2 -> RR^2$ einer Drehung im $RR^2$ für einen gegebenen Winkel $phi in RR$ bezüglich der Standardbasis $S = {e_1, e_2}$ ist eindeutig durch die Darstellungsmatrix
$
A_f^(S, S) = mat(cos(phi), -sin(phi); sin(phi), cos(phi))
$
bestimmt.
#bold[Beispiel 5.21:] Fortsetzung Beispiel 4.18. Die lineare Abbildung $f: RR^3 -> RR^3$ besitzt für die Standardbasis die Darstellungsmatrix
$
A_f^(S,S) = mat(1,-1,2;1,1,2;0,3,0) space -> space "rg(A)" = 2
$
für $S = {e_1, e_2, e_3}$. Beispiel 4.18: $"rg"(f) = dim(im(f))$.
#definition("5.22", "Spaltenrang, Zeilenrang")[
Sei $A in K^(m,n)$, $K$ ein Körper, gegeben. Die Maximalzahl linear unabhängiger Spaltenvektoren von $A$ heißt #bold[Spaltenrang] von $A$ und wird mit $"rg"_S (A)$ bezeichnet. Die Maximalzahl der linear unabhängigen Zeilenvektoren von $A$ heißt #bold[Zeilenrang] von $A$ und wird mit $rg_Z (A)$ bezeichnet.
$
==> A_f^(S,S) = mat(1, -1, 2; 1, 1, 2; 0, 3, 0) wide rg_S (A) = 2
$
] <def>
#bold[Satz 5.23:] Seien $V, W$ zwei $K$-Vektorräume mit den Basen $B = {v_1, ..., v_n}$ von $V$ und $C = {w_1, ..., w_m}$ von $W$ sowie $f in L(V, W)$ mit der Darstellungsmatrix $A_f^(B, C) = (a_(i j))_(i=1,....,m)^(j = 1, ... n) in K^(m,n)$. Dann gilt die Gleichheit
$
rg(f) = rg_S (A_f^(B,C))
$
#italic[Beweis:] Es gilt
$
f(v_j) = sum_(i = 1)^m a_(i j) w_i space j = 1, ..., n
$
Damit sind die Spaltenvektoren
$
vec(a_(1 j), a_(2 j), dots.v, a_(m j)) in K^m space j = 1, ..., n
$
die Koordinaten von $f(v_j)$ bezüglich der Basis $C$. Aufgrund der Isomorphie von $W$ und $K^m$ können damit diese Spaltenvektoren als Erzeugendensystem von $im(f)$ interpretiert werden. Damit folgt
$
rg(f) = dim(im(f)) = dim("Span"(vec(a_(1 1), a_(2 1), dots.v, a_(m 1)), ..., vec(a_(1 n), a_(2 n), dots.v, a_(m n)))) = rg_S (A)
$
#endproof
#bold[Beispiel 5.24:] Fortsetzung von Beispiel 5.21
Für die Darstellungsmatrix
$
A_f^(S, S) = mat(1, -1, 2;1, 1, 2;0, 3, 0)
$
gilt $rg(f) = 2 = rg_S (A_f^(S, S))$.
Graphische Darstellung der Ergebnisse: $V, W$ sind $K$-Vektorräume, $B = {v_1, ..., v_n}$ ist Basis von $V$, $C = {w_1, ..., w_m}$ ist Basis von $W$. Für $f in L(V, W)$ gilt
Mit Satz 5.18 und dem Struktursatz 4.8 können die Ergebnisse mit folgenden #bold[kommutativen Diagramme] zusammengefasst werden:
$
space V space -->^f space W \
Phi_B arrow.t space wide space arrow.t Phi_C \
space K^n -->_(A_f^(B,C)) K^m \
$
Solche kommutativen Diagramme sind sehr wichtige Hilfsmittel! Man erhält daraus folgenden Aussagen:
#boxedlist[
Für die gegebenen Basen $B$ und $C$ gibt es zwei Wege von $V$ nach $K^m$:
$
Phi_C^(-1) circ f = A_f^(B,C) circ Phi_B^(-1)
$
D.h.:
$
Phi_C^(-1) (f(v)) = A_f^(B,C) dot Phi_B^(-1) (v) space forall v in V
$
][
Mithilfe der inversen Abbildungen kann man auch andere Wege gehen, z.B:
$
f = Phi_C circ A_f^(B,C) dot Phi_B^(-1)
$
]
Was passiert bei der Verknüpfung von linearen Abbildungen mit den Darstellungsmatrizen?
#bold[Satz 5.25:] Seien $V, W$ und $X$ drei endlichdimensionale $K$-Vektorräume mit den Basen $B, C$ und $D$. Für gegebene $f in L(V, W) "und" g in L(W, X)$ gilt
$
A_(g circ f)^(B,D) = A_g^(C, D) dot A_f^(B,C)
$
#italic[Beweis:] Satz 4.20: $g circ f in L(V, X)$. Seien $B = {v_1, ..., v_n}$, $C = {w_1, ..., w_m}$, $D = {x_1, ..., x_s}$ und die Darstellungsmatrizen gegeben durch
$
A_f^(B, C) = (a_(i j))_(i = 1, ..., m space.thin "Zeilen")^(j = 1, ..., n space.thin "Spalten") "sowie" A_g^(C, D) = (b_(i j))_(i = 1, ..., s)^(j = 1, ..., m)
$
Dann folgt für $v_j, j = 1, ..., n$
$
(g circ f)(v_j) = g lr(size: #3em, (underbrace(sum_(k = 1)^m a_(k j) w_k, = space.thin f(v_j)) )) = sum_(k = 1)^m a_(k j) g(w_k) \
= sum_(k = 1)^m a_(k j) sum_(i = 1)^s b_(i k) x_i = sum_(i = 1)^s sum_(k = 1)^m a_(k j) b_(i k) x_i \
= sum_(i = 1)^s (sum_(k = 1)^m b_(i k) a_(k j)) x_i
$
D.h. für die Darstellungsmatrix
$
A_(g circ f)^(B, C) = (c_(i j))_(i = 1, ..., s)^(j = 1, ..., n)
$
gilt $A_(g circ f)^(B, D) = A_f^(C, D) dot A_f^(B, C)$.
#endproof
== Basiswechsel
Seien $V$ und $W$ zwei $K$-Vektorräume mit $dim(V) = n in NN$ und $dim(W) = m in NN$ mit $B = {v_1, ..., v_n}$ als Basis von $V$. Nach dem Struktursatz für Vektorräume Satz 4.8 gilt
$
Phi_B: K^n -> V, space (x_1, ..., x_n) arrow.bar sum_(i = 1)^n x_i v_i
$
Die Kunst der linearen Algebra besteht darin, zu einem gegebenen Problem, welches durch eine lineare Abbildung beschreiben werden kann, geschickt Basen zu wählen, so dass die Darstellung möglichst einfach ist.
#bold[Beispiel 5.26:] Sei $V = RR^2$. Für die Standardbasis $C = {e_1, e_2}$ erhält man
$
Phi_C = RR^2 -> V, space (x_1, x_2) arrow.bar sum_(i = 1)^2 x_i e_i \
= x_1 vec(1,0) + x_2 vec(0,1) = vec(x_1, x_2) = mat(1, 0; 0, 1) vec(x_1, x_2)
$
Die Basis $B = {e_1, e_1+e_2}$ liefert
$
Phi_B: RR^2 -> V, space (x_1,x_2) arrow.bar sum_(i = 1)^2 x_i v_i \
= x_1 vec(1,0) + x_2 vec(1,1) = vec(x_1 + x_2, x_2) = mat(1,1;0,1) vec(x_1, x_2)
$
$V$ = Ebene die durch $RR^2$ beschrieben wird.
#bold[Frage:] Darstellung von $F$ in den unterschiedlichen Basen.
#bold[Lemma 5.27:] Der Basiswechsel zwischen zwei Basen $B$ und $C$ des $K$-Vektorraums $V$ mit $dim(V) = n in NN$ ist der Isomorphismus
$
Phi_(B, C) = Phi^(-1)_C circ Phi_B
$
#italic[Beweis:] Basierend auf dem Diagramm
#align(center, figure(
image("bilder/527.jpg", width: 80%),
))
Es fehlt noch die Isomorphieeigenschaft. Nach dem Struktursatz 4.8 gilt: $Phi_B, Phi_C$ sind Isomorphismen. Dann ist auch
#boxedlist[$Phi^(-1)_C$ ein Isomorphismus][$Phi^(-1)_C circ Phi_B$ ein Isomorphismus]
siehe Satz 1.38.
#endproof
#bold[Beobachtung:] Sei $V$ ein $K$-Vektorraum mit Basis $B = {v_1, ..., v_n}$ und $C = {e_1, ..., e_n}$ die Standardbasis. Dann ist
#boxedlist[$Phi_C: K^n -> V$ die Identität, d.h. $A^(C,C)_(Phi_C) = I_n$ (siehe oben)][$Phi_(B,C) = Phi^(-1)_C circ Phi_B = Phi_B space ==> space Phi_(B,C) (e_i) = Phi_B (e_i) = v_i$]
Die zum Basiswechsel gehörende Matrix $A_(Phi_(B,C))^(B,C)$ von einer gegebenen Basis $B = {v_1, ..., v_n}$ zur Standardbasis ist die Matrix, deren Spalten den Basisvektoren von $B$ entsprechen, d.h.
$
A_(Phi_(B,C))^(B,C) = mat(v_1, v_2, ..., v_n) wide #italic[$v_i$ ist immer ein Spaltenvektor]
$
#bold[Beispiel 5.28:] Sei $V = RR^2$ und $B = {e_1, e_1+ e_2}$ sowie $C = {e_1,e_2}$. Damit ist
$
A_(Phi_(B,C))^(B,C) = mat(1,1;0,1) subset.eq "Gl"_2 (RR) space "mit"
$
$
(A_(Phi_(B,C))^(B,C))^(-1) = mat(1,-1;0,1)
$
Man erhält z.B.:
$
Phi_(B,C) (vec(1/2,1/2)) = mat(1,1;0,1) vec(1/2, 1/2) = vec(1,1/2)
$
Jetzt für lineare Abbildungen:
#bold[Lemma 5.29:] Seien $V$ und $W$ $K$-Vektorräume mit $dim(V) = n, dim(W) = m$ sowie $f in L(V, W)$. Weiter seien $B, tilde(B)$ zwei Basen von $V$ und $C, tilde(C)$ zwei Basen von $W$. Dann gilt für die Darstellungsmatrizen, dass
$
A_f^(tilde(B), tilde(C)) = Phi_(C,tilde(C)) dot A_f^(B,C) dot Phi_(B, tilde(B))^(-1)
$
bzw.
$
A_f^(B, C) = Phi_(C, tilde(C))^(-1) dot A_f^(tilde(B),tilde(C)) dot Phi_(B, tilde(B))
$
#italic[Beweis:] Dies folgt aus dem kommutativen Diagramm.
#align(center, figure(
image("bilder/529.jpg", width: 80%)
))
#bold[Beispiel 5.30:] Sei die Darstellungsmatrix der linearen Abbildung $f: V -> W$ mit $V = RR^3$ und $W = RR^2$ bezüglich der Standardbasen gegeben durch
$
A_f^(B,C) = mat(1,1,-2;-6,3,3)
$
Wir suchen jetzt die Darstellung bezüglich der Basen
$
tilde(B) = {vec(0,0,-1),vec(0,1,0),vec(1,1,1)} wide tilde(C) = {vec(2,-3), vec(1,3)}
$
Mit $v_1 = -1 dot e_3, space v_2 = e_2, space v_3 = e_1 + e_2 + e_3$ folgt aus der Linearität von $f$, dass
$
f(v_1) = f(-1 dot e_3) = -f(e_3) = w_1 \
f(v_2) = f(e_2) = w_2 \
f(v_3) = f(e_1) + f(e_2) + f(e_3) = 0
$
Also wird $f$ bezüglich der Basen $tilde(B)$ und $tilde(C)$ durch
$
A_f^(tilde(B), tilde(C)) = mat(1,0,0;0,1,0)
$
beschrieben.
#bold[Fazit:] Der richtige Basiswechsel bringt die Abbildung $f$ in sehr einfache Gestalt. Man kann zeigen: Für $V, W$ endlichdimensional und $f in L(V,W)$ mit $dim(im(f)) = r in NN$, $c = dim(V)-r$, $a = dim(W)-r$ existieren Basen $B$ von $V$ und $C$ von $W$, so dass
$
A_f^(B,C) = mat(I_r, 0_(r times b); 0_(a times r), 0_(a times b)) space "z.B. Mehrmann Satz 10.24"
$
== Elementarumformung von Matrizen
Für eine gegebene Matrix $A = (a_(i j))_(j = 1, ..., m)^(j = 1, ..., n) in K^(m, n)$ bezeichnen wir die Spaltenvektoren mit
$
a_j = vec(a_(1 j), a_(2, j), dots.v, a_(m j)) space "mit" space j = 1, ... n space ==> space a_j in K^(m, 1) isomorph K^m
$
und die Zeilenvektoren mit
$
a^i = (a_(i 1), a_(i 2), ..., a_(i n)) space "mit" space i = 1, ..., m space ==> space a_i in K^(1, n)
$
Die drei elementaren Spaltenumformungen sind gegeben durch
#box(width: 100%, inset: (left: 0.5cm))[
#bold[(S1)] Vertauschen zweier verschiedener Spalten $a_j$ und $a_k$ für $j,k in {1, ..., n}$, $j != k$
#bold[(S2)] Multiplikation einer Spalte $a_j, j in {1, ..., n}$ mit Skalar $lambda in K, lambda != 0$
#bold[(S3)] Addition einer Spalte $a_j$ zu einer anderen Spalte $a_k$ für $j, k in {1, ..., n}$, $n != k$
]
Die drei elementaren Zeilenumformungen sind gegeben durch.
#box(width: 100%, inset: (left: 0.5cm))[
#bold[(Z1)] Vertauschen zweier Zeilen $a^i$ und $a^k$ für $i, k in {1, ..., m}$, $i != k$
#bold[(Z2)] Multiplikation einer Zeile $a^i$, $i in {1, ..., m}$ mit einem Skalar $lambda in K$, $lambda != 0$
#bold[(Z3)] Addition einer Zeile $a^i$ zu einer anderen Zeile $a^k$ für $i, k in {1, ..., m}$, $i != k$
]
#bold[Lemma 5.31:] Es bezeichne $A = (a_(i j))_(j = 1, ..., m)^(i = 1, ..., n) in K^(m,n)$. Dann ändern sich der Spaltenrang $rg_S (A)$ und der Zeilenrang $rg_Z (A)$ von $A$ bei elementaren Umformungen (S1) - (S3) bzw. (Z1) - (Z3) nicht.
#italic[Beweis:] Hier: Spaltenrang
Nach Definition gilt:
$
rg_S (A) = dim("Span"(a_1, ..., a_m))
$
Dann folgt aus
(S1)
$
"Span"(a_1, ..., a_j, ...., a_k, ..., a_n) = "Span"(a_1, ..., a_k, ..., a_j, ..., a_n) \
j, k in {1, ..., n}, j != k, "o.B.d.A" j<k
$
(S2)
$
"Span"(a_1, ..., a_j, ..., a_n) = "Span"(a_1, ..., lambda a_j, ..., a_n) \
j in {1, ..., n}, lambda != 0
$
(S3)
$
"Span"(a_1, ..., a_j, ..., a_k, ..., a_n) = "Span"(a_1, ..., a_j, ..., a_k + a_j, ..., a_n) \
j,k in {1, ..., n}, j != k, "o.B.d.A." j<k
$
die Invarianz von $rg_S (A)$ für (S1) - (S3)
2. Zeilenumformungen
Wir betrachten die Koordinaten der Spaltenvektoren $a_1, ..., a_n$ bezüglich der Standardbasis $B = {e_1, ..., e_m}$ bezüglich der Abbildung in den $K^m$ welche durch $A$ gegeben ist. Durch Vertauschen der Einheitsvektoren $e_i, e_k$, $i,k in {1, ..., n}$, $i != k$ erhalten wir eine neue Basis $tilde(B) = {e_1, ..., e_k, ..., e_i, ..., e_m}$, o.B.d.A. $i<k$ für den $K^m$ und die neuen Koordinaten
$
tilde(a)_1 = vec(a_(1 1), dots.v, a_(k 1), dots.v, a_(i 1), dots.v, a_(m 1)), space ... space, tilde(a)_n = vec(a_(1 n), dots.v, a_(k n), dots.v, a_(i n), dots.v, a_(m n))
$
aus den ursprünglichen Koordinaten für $B$
$
a_1 = vec(a_(1 1), dots.v, a_(i 1), dots.v, a_(k 1), dots.v, a_(m 1)), space ... space, a_n = vec(a_(1 n), dots.v, a_(i n), dots.v, a_(k n), dots.v, a_(m n))
$
Dies entspricht (Z1), damit folgt
$
rg_S (A) = dim("Span"(a_1, ..., a_n)) = dim("Span"(tilde(a)_1, ..., tilde(a)_n))
$
Jetzt (Z2). Dies entspricht der Multiplikation des $i$-ten Einheitsvektor mit $lambda^(-1)$. D.h. man erhält die neue Basis $hat(B) = {e_1, ..., lambda^(-1) e_i, ..., e_m}$ und die zugehörigen Koordinaten
$
hat(a)_1 = vec(a_(1 1), dots.v, lambda a_(i 1), dots.v, a_(m 1)), space ... space, hat(a)_n = vec(a_(1 n), dots.v, lambda a_(1 n), dots.v, a_(m n))
$
Es folgt
$
rg_S (A) = dim("Span"(a_1, ..., a_n)) = dim("Span"(hat(a)_1, ..., hat(a)_n))
$
(Z3)
Ersetzt man den $k$-ten Einheitsvektor durch $e_k - e_i$, $i, k in{1, ..., m}$, $i < k$ o.B.d.A. Man erhält die neue Basis $caron(B) = {e_1, ..., e_i, ..., e_k - e_i, ..., e_m}$ sowie die neuen Koordinaten
$
caron(a)_1 = vec(a_(1 1), dots.v, a_(i 1), dots.v, a_(k 1), dots.v, a_(m 1)), space ... space, caron(a)_n = vec(a_(1 n), dots.v, a_(i n), dots.v, a_(k n) + a_(i n), dots.v, a_(m n))
$
Es folgt daraus wieder, dass
$
rg_S (A) = dim("Span"(a_1, ..., a_m)) = dim("Span"(caron(a)_1, ..., caron(a)_n))
$
#endproof
#bold[Beispiel 5.32:] $K = RR$ und
$
A = mat(1,1,1,1;1,2,3,4;2,3,4,5) --> A^((1)) = mat(1,1,1,1;0,1,2,3;0,1,2,3)
$
mit (Z1): $i = 1, lambda = -1$, (Z3): $k = 2, i = 1$, (Z1): $i = 1, lambda = -1$
$
--> A^((2)) = mat(1,1,1,1;0,1,2,3;0,0,0,0)
$
$
==> rg_S (A^((2))) = 2 space "und" space rg_Z (A^((2))) = 2
$
#pagebreak()
= Lineare Gleichungssysteme
Ein System von Gleichungen der Form
$
a_(1 1) x_1 + a_(1 2) x_2 + ... + a_(1 n) x_n = b_1 \
a_(1 2) x_1 + a_(2 2) x_2 + ... + a_(2 n) x_n = b_2 \
dots.v \
a_(m 1) x_1 + a_(m 2) x_2 + ... + a_(m n) x_n = b_m
$
$
<==> A x = b
$
für eine gegebene Matrix $A in K^(m,n)$, einem gegebenen Vektor $b in K^m$ und einem unbekannten Vektor $x in K^n$ heißt #bold[lineares Gleichungssystem (LGS)]. Die Lösung von linearen Gleichungssystemen ist ein zentrales Problem der linearen Algebra. Wichtige Fragen:
#box(width: 100%, inset: (left: 1cm, right: 1cm))[
1. #[
Existenz einer Lösung? Unter welchen Bedingungen besitzt (LGS) überhaupt Lösungen?
]
2. #[
Lösungsmannigfaltigkeiten: Wann (LGS) mindestens eine Lösung besitzt: Unter welchen Bedingungen gibt es genau eine Lösung? Wenn es mehrere Lösungen gibt: Wie ist die Struktur der Lösungsmenge?
]
3. #[
Lösungsverfahren: Wie kann man Lösungen von (LGS) praktisch berechnen?
]
]
#bold[Hier:] Fragen 1 + 2, etwas zu 3). Beantwortung von 3): Numerische Lineare Algebra
== Existenz von Lösungen und Lösungsmengen
#definition("6.1", "Lineares Gleichungssystem")[
Für das lineare Gleichungssystem
$
A x = b space "mit" A in K^(m, n), b in K^m
$
nennt man $A$ die #bold[Koeffizientenmatrix] und $b$ die #bold[rechte Seite]. Die Matrix
$
A_("erw") = (A b) in K^(m, n+1)
$
nennt man #bold[erweiterte Koeffizientenmatrix].
Ist $b = 0 in K^m$, so heißt (LGS) #bold[homogen], ansonsten #bold[inhomogen]. Gilt für $overline(x) in K^n$, dass $A overline(x) = b$, so nennt man $overline(x)$ eine #bold[Lösung] von (LGS). Die Menge aller Lösungen heißt #bold[Lösungsmenge] und wird mit
$
cal(L)(A, b)
$
bezeichnet.
] <def>
#bold[Bemerkung:] Im normalen Fall, d.h. sei $b = 0 in K^m$ gilt offensichtlich immer $rg_S (A) = rg_S (A_"erw")$. (Später: $rg(A) = rg(A_"erw"))$. Außerdem existiert im homogenen Fall immer eine Lösung, nämlich $x^* = 0 in K^n$. Denn es gilt $A x^* = A 0_m = 0 = b$.
Beantwortung Frage 1:
#bold[Satz 6.2:] Das LGS ist genau dann lösbar, d.h. $cal(L)(A, b) != emptyset$, wenn
$
rg_S (A) = rg_S (A_"erw")
$
gilt.
#italic[Beweis:] Seien $a_i$, $1 <= i <= n$, die Spalten von $A$ und $f: K^n -> K^m$ die zu $A$ gehörende lineare Abbildung. Dann gilt
$
"LGS lösbar" <==> exists x in K^n: A x = b <==> exists x in K^n: f(x) = b <==> b in im(f)
$
$
&<==> b in "Span"{f(e_1), ..., f(e_n)} \
&<==> b in "Span"{a_1, ..., a_n} \
&<==> "Span"{a_1, ..., a_n} = "Span"{a_1, ..., a_n, b} \
&<==> rg_S (A) = rg_S (A_"erw")
$
#endproof
#bold[Folgerung:] Ist $m<=n$ und gilt, dass $rg_S (A) = m$, so besitzt (LGS) mindestens eine Lösung.
Denn: Wegen $m<=n$ spannen die Spaltenvektoren $a_1, ..., a_m, a_(m+1), ..., a_n$ $in K^m$ von $A$ den $K^m$ auf.
$
==> rg_S (A) = m = rg_S(A_"erw")
$
#bold[Satz 6.3:] Sei $L_0 = cal(L)(A, 0)$, d.h. die Menge aller Lösungen des homogenen linearen Gleichungssystems (LGS). Dann ist $L_0 subset.eq K^n$ ein Unterraum der Dimension
$
dim L_0 = n - underbrace(rg_S (A), <=n) >= 0
$
#italic[Beweis:] Die Matrix $A in K^(m,n)$ definiert eine lineare Abbildung $f: K^n -> K^m$, $f(x) = A x$. Also gilt
$
L_0 = {x in K^n | A x = 0 } = {x in K^n | f(x) = 0 } = ker(f)
$
Lemma 4.13: $L_0$ ist Unterraum von $K^n$.
Dimensionssatz Satz 4.16: Satz 5.23.
$
dim L_0 = dim(ker(f)) =^"4.16" dim(K^n) - rg(f) =^"5.23" n - rg_S (A)
$
#endproof
#bold[Folgerungen:]
#boxedlist[
Ist $m>=n$ und gilt $rg_S (A) = n$, so besitzt (LGS) für $b = 0$ nur die triviale Lösung $x^* = 0$, denn aus dem letzen Satz folgt
$
dim L_0 = n - rg_S (A) = n - n = 0 ==> L_0 = {0}
$
][
Besitzt umgekehrt (LGS) für $b = 0$ nur $x^* = 0 in K^n$ als Lösung, d.h.
$
L_0 = {0} ==> 0 = n - rg_S (A) ==> rg_S (A) = n
$
]
#boxedlist[
Im Fall $m = n$, dann gilt für das homogene Gleichungssystem $A x = b$
$
L_0 = {0} <==> A "invertierbar, d.h." A in "GL"_n (K)
$
Alternativer Beweis:
$A in "GL"_n (K) <==>$ Es existiert die inverse Matrix $A^(-1) in "GL"_n (K)$
$
A x = 0 \
A^(-1) A x = A^(-1) 0 \
x = 0
$
]
Lösungsmenge für den allgemeinen Fall:
#bold[Satz 6.4:] Es gelte für die Lösungsmenge von (LGS), dass
$
cal(L)(A,b) != emptyset
$
D.h. die Menge aller Lösungen von (LGS) ist nicht leer. Dann gilt: Es gibt $x^* in cal(L)(A, b)$ und
$
cal(L) (A,b) = {x in K^n | x = x^* + y , y in cal(L)(A,0) }
$
D.h. die Menge aller Lösungen von (LGS) erhält man aus einer speziellen Lösung des inhomogenen linearen Gleichungssystems und Addition sämtlicher Lösungen des zugehörigen homogenen LGS.
#italic[Beweis:] Nach Vorraussetzung gilt $A x^* = b$. Damit folgt für $y in cal(L)(A, 0)$, d.h. $A y = 0$, dass
$
A(x^* + y) = A x^* + A y = b + 0 = b \
==> {x in K^n | x = x^* + y, y in cal(L)(A, 0)} subset.eq cal(L)(A, b)
$
Sei $x in cal(L)(A, b)$. Dann erhält man für $y = x^* - x$, dass
$
A y = A(x^*-x) = A x^* - A x = b - b = 0 ==> y in cal(L)(A, 0) \
==> A y = 0 ==> - A y = 0 ==> A(-y) = 0 ==> -y in cal(L)(A, 0)
$
$
cal(L)(A, b) subset.eq {x in x in K^n | x = x^* + y, y in cal(L)(A, 0)}
$
#endproof
Was ist die "Größe" des Lösungsraumes?
Problem: $cal(L)(A, b)$ ist ja kein Unterraum, da für $b != 0, x = 0 in.not cal(L)(A, b)$ gilt. Deswegen: Übertragung des Dimensionsbegriffs auf Mengen dieser Struktur.
#definition("6.5", "Affiner Unterraum")[
Sei $V$ ein $K$-Vektorraum. Eine Teilmenge $U subset V$ heißt #bold[affiner Unterraum] falls es ein $v in V$ und einen Unterrvektorraum $W$ gibt, so dass
$
U = v + W := {u in V | "es gibt ein" w in W "mit" u = v + w}
$
Die leere Menge bildet ebenfalls einen affinen Unterraum.
] <def>
Affine Unterräume kann man als "Parallelverschiebung" eines Unterraums interpretieren.
#bold[Frage:]
$
{x in K^n | x = x^* + y, y in cal(L)(A, 0)} = {x in K^n | x = tilde(x)^* + y, y in cal(L)(A,0)} \ "für" x^*, tilde(x)^* in cal(L)(A, b)"?"
$
#bold[Satz 6.6:] Sei $V$ ein $K$-Vektorraum und $U subset V$ ein affiner Untervektorraum. Der Aufhängepunkt $v in V$ kann beliebig gewählt werden. D.h. für beliebiges $tilde(v) in U$ ist $U = tilde(v) + W$. Weiter ist zu jedem affinen Unterraum $U = v + W$ der Untervektorraum $W$ eindeutig bestimmt. D.h. ist $tilde(v) in V$ und $tilde(W) subset.eq V$ ein Unterraum mit
$
v + W = tilde(v) + tilde(W)
$
so folgt $W = tilde(W)$ und $tilde(v) - v in W$
#italic[Beweis:] $U = v + W$, $tilde(v) in U ==>$ $exists overline(w) in W: tilde(v) = v + overline(w) ==>$ $v = tilde(v) - overline(w)$
1) $U subset.eq tilde(v) + W$
$
u in U ==> u = v + w "mit" w in W \
==> u = tilde(v) + underbrace(w - overline(w), in W)
$
$==> U subset.eq tilde(v) + W$
2) $tilde(v) + W subset.eq U$
$
U = tilde(v) + W =^"*" v + underbrace(overline(w) + w, in W) in U
$
$==> U = tilde(v) + W$
Sei nun $U = v + W = tilde(v) + tilde(W)$. Mit $U - U = {u - tilde(u) | u, tilde(u) in U}$ als Menge der Differenzen folgt, dass $U - U =^"(1)" W$ und $U - U =^"(2)" tilde(W)$.
$
==> W = tilde(W)
$
wir wissen: $ v + W = tilde(v) + W$
$
==> exists w in W: tilde(v) = u + w ==> tilde(v) - v = w in W
$
#endproof
#definition("6.7", "Dimension affiner Unterräume")[
Sei $V$ ein $K$-Vektorraum und $U = v + W subset V$ ein affiner Unterraum. Dann ist
$
dim U = dim W
$
die Dimension von $U$. Dies ist wegen Satz 6.6 eine sinnvolle Definition. Satz 6.4 + Satz 6.3 liefern, dass
$
dim cal(L)(A, b) = dim cal(L)(A, 0) = n - rg_S (A)
$
] <def>
Damit folgt
#bold[Korollar 6.8:] Für $A in K^(n,n)$ und $b in K^n$ sind folgende Bedingungen äquivalent:
#box(width: 100%, inset: (left: 1cm, right: 1cm))[
#sspace
1. #[
Das LGS $A x = b$ ist eindeutig lösbar
Überlegung:
$
cal(L)(A, b) = x^* + underbrace(cal(L)(A, 0), = {0})
$
]
2. $rg_S (A) = rg_S (A_"erw") = n$
]
#bold[Lemma 6.9:] Sind $A in K^(m, n)$, $b in K^m$ und $S in K^(m,m)$, so gilt
$
cal(L)(A, b) subset.eq cal(L)(S A, S b)
$
Ist $S$ invertierbar, so gilt sogar
$
cal(L)(A, b) = cal(L)(S A, S b)
$
#italic[Beweis:] Übungsaufgabe
#endproof
== Der Gauß-Algorithmus
#bold[Bemerkung:]
#boxedlist[benannt nach Carl-Friedrich-Gauß (1777 - 1855)][
Ein ähnliches Verfahren findet man in
#v(-6pt)
#align(center, "'Neun Bücher zu arithmetische Technik' (ca. 200 v. Chr. in China)")
][
siehe LR-(bzw LK) Zerlegung in der numerischen linearen Algebra
]
Wann ist ein LGS einfach lösbar?
wenn
#figure(
image("bilder/62_.jpeg", width: 80%)
)
Diese Gestalt der Matrix $A$ heißt #bold[Treppennormalform] (wird auch als Echelon-Form oder normierte Zeilenstufenform bezeichnet).
Warum einfach?
Spaltenvertauschungen ändern den Rang nicht und können als Multiplikation mit einer invertierbaren Matrix interpretiert werden.
$==>$ Lösungsraum bleibt gleich
Dies liefert
#figure(
image("bilder/62_1.jpeg", width: 80%)
)
1. #[
Es existiert genau eine Lösung, wenn
$
rg_S (A) = rg_S (A_"erw") space <==> b_(r+1) = ... = b_m = 0
$
]
2. #[
Mit $rg_S (A) = rg_S (A_"erw")$, dann ist eine spezielle Lösung gegeben durch
$
&x^* in K^n space "mit" \
&x^*_1 = b_1, ..., x_r^* = b_r, space x^*_(r+1) = ... = x_1^* = 0
$
]
3. #[
Für $b = 0 in K^m$ erhält man das zugehörige homogene Gleichungssystem
$
cal(L)(A, b) = x^* + cal(L)(A, 0)
$
Basis von $cal(L)(A, 0)$? $space dim cal(L)(A, 0) = n - r = n - rg_S (A)$
$
"Basisvektoren der Form:" wide vec(-a_(1 r + i), -a_(2 r + i), dots.v , -a_(r + r i), 0, 1, 0, dots.v, 0), wide i = 1, .., n-r, wide 1 "bei der" r+i"-ten Zeile"
$
]
#bold[Deswegen:] Gegeben ist ein (LGS)
#bold[Ziel:] Umformung von (LGS), sodass die resultierende Matrix normalisierte Treppenstufen hat und sich die Lösungsmenge nicht ändert.
Dazu: Elementarmatrizen (geht auch für $R =$ kommutativer Ring mit $1$)
hier: $A in K^(m,n)$, $K$ Körper
#boxedlist[
$m in NN$, $i,j in {1, ..., m}$, $I_m in K^(m,m)$ als Einheitsmatrix
#h(-2pt)
$e_i corres$ $i$-ter Einheitsvektor
#h(-2pt)
$==> I_m = (e_1, e_2, ..., e_m)$
][
#v(5pt)
$E_(i j) = e_i e_j^top = mat(0_m, ..., 0_m, e_i, 0_m, ..., 0_m) in K^(m,m)$
D.h. der Eintrag $(i, j)$ der Matrix $E_(i j)$ ist $1$, alle anderen Einträge sind $0$.
][
für $m >= 2$, $i, j in {1, ..., m}$ und $i < j$ die Matrizen
$
P_(i j) = mat(e_1, ..., e_(i - 1), e_j, e_(i + 1), ..., e_(j -1), e_i, e_(j + 1), ..., e_m) in K^(m,m)
$
Die Matrix $P_(i j)$ ist eine Permutationsmatrix. D.h. multipliziert man $A in K^(m,n)$ mit $P_(i j)$, so werden die Zeilen $i$ und $j$ von $A$ vertauscht.
ohne Beweis, dafür ein Beispiel:
$
A = mat(1,2,3,4;5,6,7,8;9,10,11,12) space P_(1 2) = mat(0,1,0;1,0,0;0,0,1) ==> P_(1 2) dot A = mat(5,6,7,8;1,2,3,4;9,10,11,12)
$
$corres$ Zeilenumformung (Z1). $P_(i j) in "GL"_m (K)$
Analog: $tilde(e_i) in K^n$ Einheitsvektoren aus $K^n$
$tilde(P)_(i j) in K^(n,n)$ $corres$ Spaltenumformung (S1). $tilde(P)_(i j) in "GL"_n (K)$
][
für $m>=2, i, j in {1, ..., m}$ und $i <j$ sind die Matrizen
$
G_(i j) (lambda) = I_m + lambda E_(i j) = mat(e_1, ..., e_(j - 1), e_j + lambda e_i, e_(j+1), ..., e_m) in K^(m, m)
$
D.h. die $j$-te Spalte von $G_(i j) (lambda)$ ist $e_j + lambda e_i$. Multipliziert man $A in K^(m,n)$, so wird das $lambda$-fache der $i$-ten Zeile von $A$ zur $j$-ten Zeile von $A$ addiert.
Das Produkt $space G_(i j) (lambda)^T dot A space$ bewirkt, dass das $lambda$-fache der $j$-ten Zeile zur $i$-ten Zeile von $A$ addiert wird.
]
#boxedlist[
$lambda in K$, $i in {1, ..., m}$, $M_i (lambda) := (e_1, ..., e_(i-1), lambda e_i, e_(i+1), ..., e_m) in K^(m,m)$
$==>$ Multipliziert man $A$ von links mit $M_i (lambda)$, so wird die $i$-te Zeile von $A$ mit $lambda$ multipliziert $corres$ (Z2) für $lambda != 0$
]
#bold[Beobachtung:] $P_(i j), G_(i j) (lambda), M_i (lambda)$ sind für $lambda != 0$ invertierbar!
Damit: Beweis, dass $A x = b$ in einfachere Form gebracht werden kann, #bold[ohne] die Lösungsmenge zu ändern.
#bold[Satz 6.10:] Sei $K$ ein Körper und $A in K^(m,n)$. Dann existieren invertierbare Matrizen $S_1, ..., S_t$ $in K^(m,m)$ als Produkte der oben eingeführten Elementarmatrizen, so dass
$
C := S_t dots.h.c S_2 S_1 A
$
in #bold[Treppennormalform] ist, d.h.
#figure(
image("bilder/610_1.jpg", width: 100%)
)
Genauer: $C = (c_(i j))$ ist entweder die Nullmatrix oder es gibt eine Folge von natürlichen Zahlen $j_1, ..., j_r$ als Stufen der Treppennormalform mit $1<=j_1<j_2<...<j_r<=n$ und $1<=r<="min"{m,n}$, so dass
#boxedlist[
#text(fill: rgb("#82218B"))[$square.filled$] $c_(i j) = 0 space.third space "für" space 1 <= i <= r space space "und" 1<=j <j_i space space 1<=i<=r$
][
#text(fill: rgb("#000276"))[$square.filled$] $c_(i j) = 0 space.third space "für" space 1<=i <= m space "und" 1<=j <=n$
][
#text(fill: rgb("#7884A2"))[$square.filled$] $c_(i j_i) = 1 space "für" space 1<= i <= r$
][
#text(fill: rgb("#7098DA"))[$square.filled$] $c_(l j_i) = 0 space "für" space 1<=l<j_i #h(12pt) 1 <=i <= r$
]
#bold[Bemerkungen:]
#boxedlist[
Ist $n = m$, so ist $A in K^(n,n)$ genau dann invertierbar, wenn $C = I_n$, denn
"$<==$":
$
I_n = C = underbrace(S_t dots.h.c S_1, =: A^(-1)) A
$
"$==>$": $A$ invertierbar und $S_1, ..., S_t$ invertierbar. Das Produkt von invertierbaren Matrizen ist invertierbar $==>$ $C$ invertierbar $==>$ $C$ kann keine Nullzeilen bzw. Spalten enthalten $==>$ $C = I_n$
]
#boxedlist[
Da Spaltenvertauschungen den Spaltenrang einer Matrix nicht ändern (Lemma 5.31) ist nun folgende Definition sinnvoll:
Der #bold[Rang einer Matrix] $rg(A)$ einer Matrix $A in K^(m,n)$ ist definiert als
$
rg (A) = rg_S (A) =^"6.10" rg_Z (A)
$
Außerdem folgt
$
rg (A) = rg (A^top)
$
][
Es gibt eine Verallgemeinerung der Treppennormalform für Matrizen über Ringen. Diese Hermit-Normalform spielt eine Rolle in der Zahlentheorie.
]
#italic[Beweis:] Ist $A = 0 in K^(m,n)$, dann folgt mit $S_1 = I_m, t=1$
$
S_1 A = 0 space checkmark
$
Für $A != 0$ sei $j_1$ der Index der ersten Spalte von
$
A^((1)) = (a^((1))_(i j)) := A
$
die nicht aus lauter Nullen besteht.
#v(-5mm)
#figure(
image("bilder/610_2.jpeg", width: 40%)
)
#v(-5mm)
Sei $a^((1))_(i_1 j_1)$ das erste Element in dieser Spalte welches nicht Null ist.
#v(-5mm)
#figure(
image("bilder/610_3.jpeg", width: 40%)
)
#v(-5mm)
Jetzt: Vertauschen der Zeilen $1$ und $i_1$ falls $i_1 > 1$ und normieren der ersten Zeile durch Multiplikation mit $(a^((1))_(i_1 j_1))^(-1)$ liefert eine $1$ an der Stelle $(1, j_1)$
#figure(
image("bilder/610_4.jpg", width: 60%)
)
Anschließend werden alle Einträge unterhalb des Eintrags $(1, j_1)$ mit Wert $1$ eliminiert und man erhält
#figure(
image("bilder/610_56.jpeg", width: 100%)
)
mit $A^((2)) in K^(m-1, n-j_1)$. Ist $A^((2)) = ()$, d.h. $m-1 = 0, n-j_1 = 0$ oder $A^((2)) = 0$ $in K^(m-1, n -j_1)$, sind wir fertig, da $C := S_1 A$ in Treppenform ist und $t = 1$.
Ist mindestens ein Eintrag von $A^((2))$ ungleich Null, so führt man die obigen Schritte für die Matrix $A^((2))$ aus.
Für $k = 2, 3, ...$ werden die Matrizen $S_k$ rekursiv durch
#figure(
image("bilder/610_78.jpeg", width: 50%)
)
wobei die Matrix $tilde(S)_k$ analog zu $S_1$ konstruiert wird.
$S_k$ ist wieder ein Produkt von Elementarmatrizen. Dieses Verfahren bricht nach $r <= min{m,n}$ Schritten ab. Wenn entweder $A^((r+1)) = 0$ oder $A^((r+1)) = ()$. $==>$ Nach $r$ Schritten erhält man damit die Zeilenstufenform.
#figure(
image("bilder/610_9.jpg", width: 60%)
)
#figure(
image("bilder/610_10.jpg", width: 60%)
)
$
S = S_t dots.h.c S_1
$
#italic[Beweis:]
#figure(
image("bilder/610_11.jpg", width: 30%)
)
#figure(
image("bilder/610_12.jpg", width: 80%)
)
Nach $r$ Schritten
#figure(
image("bilder/610_13.jpg", width: 60%)
)
Mit Einsen an Stellen $(1, j_1), (2, j_2), ..., (r, j_r)$. Gilt $r = 1$, so ist $S_1 A$ in normalisierter Treppenform. $checkmark$
Jetzt $r > 1$
$
==> "Einträge über den Einsen müssen den Wert 0 bekommen"
$
Dazu berechnet man rekursiv für $k = 2, ..., r$
$
R^((k)) = S_(r+k-1) "mit" \
S_(r+k-1) = G_(1, k) (-r^(k-1)_(1, j_k)) dot ... dot G_(k-1, k) (-r^(k-1)_(k-1, j_k))
$
$t = 2r-1$ ist dann die Matrix
$
C = S_t S_(t-1) dots.h.c S_1 A "in Treppennormalform"
$
#endproof
Zur Lösung von lin. Gleichungssystemen.
$
A x = b wide S A x = S b
$
Auf dem Übungsblatt haben wir bewiesen
$
S in "GL"_m (K) ==> cal(L)(S A, S b) = cal(L)(A, b)
$
$==> A_"erw" = (A b)$. Dann wähle $S$, so dass $S A_"erw"$ die normalisierte Treppenform besitzt.
#figure(
image("bilder/610_14.jpg", width: 60%)
)
$x_(j k) = tilde(b)_k wide k = 1, ..., r wide x_i = 0 "sonst"$
Eine Lösung existiert, wenn $tilde(b)_(r+1) = ... = tilde(b)_m = 0$.
#pagebreak()
= Determinanten von Matrizen
Sei $K$ ein Körper, $n in NN$. Die Determinante
#boxedlist[
ist eine Abbildung, die jeder quadratischen Matrix $A in K^(n,n)$ ein Element aus $K$ zuorndet
$
det: K^(n,n) -> K
$
][
liefert notwendige Bedingungen dafür, dass eine Matrix $A in K^(n,n)$ invertierbar ist.
][
bildet die Grundlage für die Definition des charakteristischen Polynoms einer Matrix $A in K^(n,n)$ (siehe LinA II)
][
trägt in der analytischen Geometrie zur Berechnung von Volumen einfacher Mengen bei.
][
spielt eine wichtige Rolle in Transformationsformeln von Integralen in der Analysis mehrerer Verändlicher.
]
<NAME> (1646 - 1716) gab 1690 eine Formel zur Berechnung von Determinanten an. Karl Weierstraß (1815 - 1897) führte die Determinanten über axiomatische Eigenschaften ein.
== Definitionen und grundlegende Eigenschaften
Zwei motivierende Beispiele:
Lösung linearer Gleichungssysteme
#boxedlist[
Gegeben sei ein lineares Gleichungssystem $#sspace$
$
a_(1 1) x_1 + a_(1 2) x_2 = b_1 wide &"I" \
a_(2 1) x_1 + a_(2 2) x_2 = b_2 wide &"II"
$
Die Lösung für beliebige Werte der Koeffizienten?
$
a_(2 2) "I" - a_(1 2) "II" ==> \
(a_(1 1) a_(2 2) - a_(1 2) a_(2 1)) x_1 = a_(2 2) b_1 - a_(1 1) b_2
$
Als Ausdruck für $x_1$ und
$
a_(1 1) "II" - a_(2 1) "I" ==> \
(a_(1 1) a_(2 2) - a_(1 2) a_(2 1)) x_2 = a_(1 1) b_2 - a_(2 1) b_1
$
]
#box(width: 100%, inset: (left: 1cm, right: 1cm))[
Mit der Abbildung $det: K^(2,2) -> K$
$
det(mat(a, b;c, d)) = a d - b c
$
erhält man die Lösungsformeln
$
x_1 = det mat(b_1, a_(1 2); b_2, a_(1 2)) dot (det mat(a_(1 1), a_(1 2); a_(2 1), a_(2 2)))^(-1) \
x_2 = det mat(a_(1 1), b_1; a_(2 1), b_2) dot (det mat(a_(1 1), a_(1 2); a_(2 1), a_(2 2)))^(-1)
$
Dies ist die sogenannte Cramersche Regel für $n = 2$. Sie kann für $n >= 2$ verallgemeinert werden.
ACHTUNG: Man sollte die Cramersche Regel wirklich nie zur Lösung von linearen Gleichungssystem verwenden!
$
x_1 = det mat(b_1, a_(1 2); b_2, a_(2 2)) dot (det (A))^(-1) wide x_2 = det mat(a_(1 1), b_1; a_(2 1), b_2) dot (det (A))^(-1)
$
Warum ist die Cramersche Regel trotzdem interessant?
$x_i$ berechenbar, wenn $det (A) != 0 in K$
$
det (A) = 0 <==> a_(1 1) a_(2 2) - a_(1 2) a_(2 1) = 0 \
<==> a_(2 2) vec(a_(1 1), a_(1 2)) - a_(1 2) vec(a_(2 1), a_(2 2)) = vec(0 ,0)
$
D.h. die Spalten von $A$ sind linear abhängig $==> rg (A) < 2 ==>^"Korollar 6.8"$ es existiert keine eindeutige Lösung.
]
#boxedlist[
Flächenberechnung für Parallelogramme:
Die Fläche eines Dreiecks ist gegeben durch
$
1/2 dot "Grundfläche" dot "Höhe"
$
Beweis z.B. durch das Cavalierische Prinzip, wobei
#box(width: 100%, inset: (left: 0.5cm, right: 0.5cm))[
1. #[
das Dreieck zu einem Parallelogramm ergänzt wird $#sspace$
#figure(
image("bilder/71_1.jpeg", width: 20%)
)
]
2. #[
"Verschieben" des Parallelogramms zu einem Rechteck
#figure(
image("bilder/71_2.jpeg", width: 20%)
)
]
]
]
#box(width: 100%, inset: (left: 1.5cm, right: 1.5cm))[
Zur Beschreibung dieser Fläche in der Ebene nehmen wir an, dass sie durch zwei Vektoren
$
v = vec(a, b) wide w = vec(c, d), wide v, w in RR^2
$
gegeben ist.
#figure(
image("bilder/71_3.jpg", width: 60%)
)
$
v = rho v' = rho vec(cos beta, sin beta) wide w = sigma w' = sigma vec(cos alpha, sin alpha)
$
mit $rho, sigma > 0$. Bezeichnet $F$ bzw. $F'$ die Fläche des von $v$ und $w$ bzw. $v'$ und $w'$ aufgespannten Parallelogramms, so erhält man für $0 <= beta - alpha <= pi$, dass
$
h' = sin(beta-alpha) = cos alpha sin beta - cos beta sin alpha \
= det mat(cos alpha, sin alpha; cos beta, sin beta)
$
und damit auch
$
F = rho sigma F' = rho sigma h' = rho sigma det mat(cos alpha, sin alpha; cos beta, sin beta) >= 0
$
Im Fall $sin(beta - alpha) >= 0$ entspricht die Fläche des Parallelogramms damit der skalierten Determinante.
]
#bold[Beobachtungen:]
#box(width: 100%, inset:(left: 1cm, right: 1cm))[
1. #[
$#sspace$
#figure(
image("bilder/71_4.jpeg", width: 100%)
)
]
]
#box(width: 100%, inset:(left: 1cm, right: 1cm))[
#box(width: 100%, inset:(left: 0.5cm, right: 0.5cm))[
Auswirkungen auf die Fläche
D.h. für $lambda, mu in RR$ sollte gelten
$
det vec(mu v, w) = mu det vec(v, w) space "sowie" space det vec(v, lambda w) = lambda det vec(v,w)
$
mit $v = mat(a, b)$ und $w = mat(c, d)$.
]
2. #[
Nach dem Cavalierischen Prinzip ist die Fläche unabhängig vom Scherungswinkel:
#figure(
image("bilder/71_5.jpg", width: 50%)
)
D.h. für $lambda in RR$ sollte gelten
$
det vec(v, w) = det vec(v, w + lambda v)
$
für $v = mat(a, b)$ und $w = mat(c, d)$.
]
3. #[
#v(5pt)
#figure(
image("bilder/71_6.jpg", width: 20%)
)
#v(-5pt)
Fläche $1 ==>$
$
det vec(e_1^top, e_2^top) = det mat(1,0;0,1) = det I_2 = 1
$
]
4. #[
$-->^w -->^v "oder" <--^w -->^v space ==> det vec(v,w) = 0$
]
]
Basierend auf diesen Beobachtungen:
#definition("7.1", "Determinante")[
Eine Abbildung
$
det: K^(n,n) -> K, space A arrow.bar det (A)
$
heißt #bold[Determinante] falls gilt:
#bold[D1.] $det$ ist linear in jeder Zeile, d.h. für jeden Index $i in {1, ..., n}$ gilt
1. #[
Ist $a_i = a_i^' + a_i^('')$ so ist $#sspace$
$
det vec(dots.v, a_i, dots.v) = det vec(dots.v, a_i^', dots.v) + det vec(dots.v, a_i^'', dots.v)
$
]
2. #[
Ist $a_i = lambda a_i^'$ für $lambda in K$, so ist
$
det vec(dots.v, a_i, dots.v) = lambda det vec(dots.v, a_i^', dots.v)
$
]
#bold[D2.] $det$ ist #bold[alternierend], d.h. hat $A$ zwei gleiche Zeilen, so gilt $det (A) = 0$
#bold[D3.] $det$ ist normiert, d.h. $det (I_n) = 1$
] <def>
#bold[Bemerkung:]
#boxedlist[
Definition ist sehr einfach, aber sehr mächtig, siehe D4 - D13
][
Existenz und Eindeutigkeit einer solchen Abbildung sind noch zu zeigen.
]
#bold[Satz 7.2:] Eine Determinante
$
det: K^(n,n) |-> K
$
hat die folgenden weiteren Eigenschaften:
#bold[D4.] Für jedes $lambda in K$ gilt $det (lambda A) = lambda^n det (A)$
#bold[D5.] Ist eine Zeile von $A$ gleich 0, so gilt $det (A) = 0$
#bold[D6.] Ist $B$ eine Matrix die aus $A$ durch Zeilenvertauschungen entsteht (Z1), so gilt $det (B) = - det (A)$
#bold[D7.] Ist $lambda in K$ und entsteht $B$ aus $A$ durch Addition der $lambda$-fachen $j$-ten Zeile zur $i$-ten Zeile ($i!=j$) (Z2+Z3) so ist $det B = det A$
#bold[D8.] Ist $A$ eine obere Dreiecksmatrix
$
A = mat(lambda_1,ast,ast;0,dots.down,ast;0,0,lambda_n)
$
so ist $det A = lambda_1 dot ... dot lambda_n$ #text(fill: red, size:24pt)[!]
#bold[D9.] Ist $n >= 2$ und $A in K^(n,n)$ von der Gestalt
$
A = mat(A_1, B; 0, A_2)
$
wobei $A_1$ und $A_2$ quadratisch sind, d.h. $A_1 in K^(n_1, n_1)$ und $A_2 in K^(n_2,n_2)$ mit $n_1 + n_2 = n$, so gilt $det A = det A_1 dot det A_2$
#bold[D10.] $det A = 0$ ist äquivalent zu $rg A < n$
#bold[D11.] Für Matrizen $A, B in K^(n,n)$ gilt der Determinanten-Multiplikationssatz, d.h.
$
det (A dot B) = det A dot det B
$
Insbesondere gilt damit für $A in "GL"_n (K)$, dass $det A^(-1) = (det A)^(-1)$.
#bold[D12.] $det A^top = det A$. D.h. die obigen Aussagen für Zeilen gelten analog für Spalten.
#bold[D13.] #bold[Achtung:] Für Matrizen $A, B in K^(n,n)$ ist im Allgemeinen $det (A+B) != det A + det B$
#italic[Beweis:] D4 und D5 folgen direkt aus D1.
#bold[D6.] O.B.d.A $i<j$. Dann gilt wegen D1.1 und D2
$
det A + det B = det vec(dots.v, a_i, dots.v, a_j, dots.v) + det vec(dots.v, a_j, dots.v, a_i, dots.v) \
= underbrace(det vec(dots.v, a_i, dots.v, a_i, dots.v), = 0) + det vec(dots.v, a_i, dots.v, a_j, dots.v) - det vec(dots.v, a_j, dots.v, a_i, dots.v) - underbrace(det vec(dots.v, a_j, dots.v, a_j, dots.v), = 0) \
=^"D1.1" det vec(dots.v, a_i, dots.v, a_i + a_j, dots.v) + det vec(dots.v, a_j, dots.v, a_i + a_j, dots.v) =^"D1.1" det vec(dots.v, a_i + a_j, dots.v, a_i + a_j, dots.v) =^"D2" 0
$
#bold[D7.] O.B.d.A $i<j$. Wegen D1 und D2 gilt
$
det B = det vec(dots.v, a_i + lambda a_j, dots.v, a_j, dots.v) =^"D1.1" det vec(dots.v, a_i, dots.v, a_j, dots.v) + det vec(dots.v, lambda a_j, dots.v, a_j, dots.v) = det A + lambda underbrace(det vec(dots.v, a_j, dots.v, a_j, dots.v), = 0) =^"D2" det A
$
#bold[D8.] Sind alle $lambda_i != 0$, so folgt durch wiederholte Anwendung von D7, dass
$
det A = det mat(lambda_1, 0, 0; 0, dots.down, 0;0,0,lambda_n) =^"D1.2" lambda_1 dot ... dot lambda_n dot underbrace(det I_n, = 1 "(D3)")
$
Gibt es ein $lambda_i = 0$, so wählen wir $i$ maximal, d.h. $lambda_(i + 1) != 0, ..., lambda_n != 0$. Dann kann der Rest der $i$-ten Zeile, also $a_(i i + 1), ..., a_(i n )$ auf den Wert Null gebracht werden. Mit D7 folgt, dass dies die Determinante nicht ändert. Damit erhalten wir eine Nullzeile und aus D5 folgt dann $det A=0$
#bold[D9.] $A_1 in K^(n_1, n_1)$. Mit den Zeilenumformungen (Z1), (Z2)+(Z3) kann $A_1$ zu einer oberen Dreiecksmatrix $C_1$ umgeformt werden. Es gilt mit D6 und D7 dass $det A_1 = (-1)^k det C_1$
$
mat(A_1, B;0, A_2) --> mat(C_1, tilde(B);0, A_2)
$
Also ist $A_2$ unverändert.
Dann erzeugt man wieder mit (Z1), (Z2)+(Z3) aus $A_2$ eine obere Dreieckmatrix $C_2$, dabei bleiben $C_1$ und $tilde(B)$ unverändert und es gilt
$
det A_2 = (-1)^l det C_2
$
Für
#figure(
image("bilder/72_1.jpg", width: 60%)
)
mit $C_1, C_2$ obere Dreieckmatrizen gilt
$
det C = det C_1 dot det C_2 \
det A = (-1)^(k + l) det C = (-1)^(k+l) det (C_1) dot det (C_2) \
= (-1)^(k+l) (-1)^k det (A_1) (-1)^l det (A_2) = (-1)^(2k+2l) det (A_1) dot det (A_2) \
= det (A_1) dot det (A_2)
$
#bold[D10.] Durch Zeilenumformungen (Z1), (Z2)+(Z3) bringen wir $A$ auf Zeilenstufenform
$
B = mat(lambda_1, ast, ast;0, dots.down, ast;0,0,lambda_n)
$
Wegen D6+D7 gilt $det (A) = plus.minus det (B)$. Weiter ist $rg (A) = rg (B)$ (Lemma 5.31). Aus D8
$
rg (B) = n <==> det (B) = lambda_1 dot ... dot lambda_n != 0
$
#bold[D11.] Ist $rg (A) < n$, so ist $rg (A dot B) < n$ (siehe Übungsaufgabe). Damit erhält man aus D10
$
0 = 0
$
Ist $rg (A) = n ==> A in "GL"_n (K)$. Dann gibt es nach Satz 6.10 invertierbare Matrizen
Satz 6.10: $C = S_t dots.h.c S_1 A$ in Treppennormalform
$==> C = I_n$
$==> A = S_1^(-1) dots.h.c S_(t-1)^(-1) S_t^(-1) I_n wide (*)$
$==>^"D3" det I_n = 1$
$S_i$ $corres$ Produkt von $G_(i j) (lambda), M_i (lambda), P_(i j)$ $==>$ $S_i^(-1) corres$ Produkt von $G_(i j)^(-1) (lambda), M_i^(-1) (lambda), P_(i j)^(-1)$
Sei $D in K^(n,n)$, dann gilt
$
det (underbrace(G_(i j)^(-1) (lambda) D, *)) = space ?
$
$*$: Subtrahieren eines Vielfachen einer Zeile von einer anderen
$
det (G_(i j)^(-1) (lambda)) =^"D7" det I_n = 1 \
tilde(D) = G_(i j)^(-1) (lambda) D ==> det (tilde(D)) =^"D7" det D \
==> det (G_(i j)^(-1) (lambda) D) = det (G_(i j)^(-1) (lambda)) dot det (D) = det (D)
$
Analog folgt:
$
det (P_(i j)^(-1) (lambda) D) = underbrace(det (P_(i j)^(-1) (lambda)), -1) dot det (D) \
det (M_i^(-1) (lambda) D) =^"D1.2" det (M_i^(-1) (lambda)) dot det (D)
$
induktiv folgt: $det (S_i^(-1) D) = det (S_i^(-1)) dot det (D) wide (star)$
$
==> det (A) = det (S_1^(-1)) dot dots.h.c dot det(S_t^(-1)) dot 1 \
==> det (A dot B) =^((*)) det (S_1^(-1) dot dots.h.c dot S_t^(-1) B) \
=^((star)) det (S_1^(-1)) dot dots.h.c dot det (S_t^(-1)) dot det (B) \
= det (A) dot det (B)
$
$A in "GL"_n (K) ==> exists A^(-1): A dot A^(-1) = I_n$
$
1 =^"D3" det (I_n) = det (A dot A^(-1)) = det (A) dot det (A^(-1)) \
==> det (A^(-1)) = (det (A))^(-1)
$
#bold[D12.] $rg (A) < n$:
Mit Lemma 5.31: $rg (A^top) < n$ (Zeilenrang = Spaltenrang)
Mit D10 folgt: $det (A) = 0 = det (A^top)$
Sei $rg (A) = n$ und sei $A$ wie in D11:
$
A = S_1^(-1) dot dots.h.c dot S_t^(-1)
$
Dann gilt
$
det (A^top) = det (S_t^(-top) dot S_(t-1)^(-top) dot dots.h.c dot S_1^(-1)) =^"D11" det (S_t^(-top)) dot det (S_(t-1)^(-top)) dot dots.h.c dot det (S_1^(-1))
$
induktiv und analog zu oben folgt:
$
det (S_t^(-top)) = det (S_t^(-1)) \
==> det (A^t) = det (S_t^(-top)) dot dots.h.c dot det (S_1^(-1)) \
=^"D11" det (S_t^(-1) dot dots.h.c dot S_1^(-1)) = det (A)
$
#bold[D13.] Für $K = RR, A = I_2, B = I_2$
d.h. $A, B in RR^(2,2)$. Dann gilt:
$
det (A + B) = det (0_(2 times 2)) =^"D8" 0 \
det (A) + det (B) = 1 + 1 = 2 space.thin arrow.zigzag
$
#endproof
#bold[Beispiel 7.3:] Berechnung einer Determinante
Für $A in RR^(n,n)$ kann man eine Determinante berechnen, indem man $A$ auf obere Dreiecksgestalt bringt.
$
A = mat(1,2,0;1,4,1;1,-2,2) --> A_1 = mat(1,2,0;0,2,1;0,-4,2) = G_(3 1) (-1) G_(2 1) A
$
($->$ von Zeile 3 wird Zeile 1 mit $-1$ abgezogen)
$
==> det (A_1) = ^"D8" underbrace(det (G_(3 1) (-1)), = 1) dot underbrace(det (G_(2 1) (-1)), = 1) dot det (A) \
A_2 = mat(1,2,0;0,2,1;0,0,4) = G_(3 2) (2) dot A_1
$
$
8 = det (A_2) = det (G_(3 2) (2)) dot det (A_1) = underbrace(det (G_(3 2) (2)), = 1) dot det (A)
$
== Existenz und Eindeutigkeit
#bold[Frage:] Ist die Berechung der Determinante eindeutig? Oder hängt sie von der Reihenfolge der Zeilenumformungen ab?
#definition("7.4", "Permutation")[
Sei $n in NN$. Eine bijetkive Abbildung $#sspace$
$
sigma: {1, 2, ..., n} -> {1, 2, ..., n}, space j arrow.bar sigma(j)
$
heißt #bold[Permutation] der Zahlen ${1, ..., n}$. Die Menge aller dieser Abbildungen nennt man $S_n$ und man schreibt eine Permutation $sigma in S_n$ in der Form
$
[sigma(1) space space sigma(2) space space dots space space sigma(n)]
$
] <def>
#bold[Frage:] Gilt für ein gegebenes $sigma in S_n$ und
$
I_sigma = vec(e^top_(sigma(1)), dots.v, e^top_(sigma(n)))
$
$det (I_sigma) = plus.minus 1 space.thin$?
#definition("7.5", "Transposition")[
Seien $n in NN$, $n >= 2$. Eine Permutation $cal(T) in S_n$ heißt #bold[Transposition], wenn $cal(T)$ nur zwei Elemente aus ${1,2, ..., n}$ vertauscht und alle andere unverändert bleiben. D.h. es existieren $k, l in {1, ..., n}$ so, dass
$
cal(T) (k) = l, cal(T) (l) = k, cal(T) (i) = i wide i in {1, ..., n} without {k, l}
$
] <def>
#bold[Lemma 7.6:] Ist $n >= 2$, so existieren zu jedem $sigma in S_n$ Transpositionen $cal(T)_1, ..., cal(T)_k in S_n$ mit
$
sigma = cal(T)_1 circ cal(T)_2 circ dots circ cal(T)_k
$
#italic[Beweis:] Ist $sigma = id$ und $cal(T)$ eine Transposition, dann gilt
$
id = sigma = cal(T) circ cal(T)
$
Ist $sigma != id$, so existiert ein $i_1 in {1, ..., n}$ mit
$
sigma(i) = i space "für" space i = 1, ..., i_1 - 1 space "und" space sigma(i_1) > i_1
$
Sei $cal(T)_1$ die Transposition, die $i_1$ mit $sigma(i_1)$ vertauscht und $sigma_1 := cal(T)_1 circ sigma$
Dann gilt
$
sigma_1 (i) = i space "für" space i = 1, ..., i_1
$
Ist $sigma_1 = id$ so gilt $sigma = cal(T)_1^(-1) = cal(T)_1$, sonst existiert ein $i_2$ mit $i_2 > i_1$ und
$
sigma_1 (i) = i space "für" space i = 1, ..., i_2 - 1 space "und" space sigma_1 (i_2) > i_2
$
induktiv erhält man $k <= n$ Transpositionen
$
&cal(T)_1, ..., cal(T)_k space "mit" \
&sigma_k = cal(T)_k circ dots circ cal(T)_1 circ sigma = id \
==> &sigma = cal(T)_1^(-1) circ dots circ cal(T)_k^(-1) = T_1 circ dots circ T_k
$
#endproof
Die Transpositionen sind nicht eindeutig bestimmt! Für die Entscheidung über das Vorzeichen
$
det (I_sigma) = plus.minus 1
$
müssen wir zeigen, dass die Anzahl der Transpositionen immer gerade oder immer ungerade ist.
#definition("7.7", "Fehlstand")[
Seien $n in NN$, $n >= 2$ und $sigma in S_n$. Ein Paar $(i, j) in N times N$ mit $1 <=i < j <=n$ und $sigma (i) > sigma (j)$ nennt man #bold[Fehlstand] von $sigma$. Ist $k$ die Anzahl der Fehlstände von $sigma$, so heißt $sgn(sigma)$ das #bold[Signum] oder Vorzeichen von $sigma$. Für $n = 1$ setzt man $sgn([1]) := 1 = (-1)^0$
$
sgn(sigma) = (-1)^k
$
] <def>
#bold[Beobachtung:] Für $sigma = [3 space space 2 space space 1]$ ($3 = sigma(1), 2 = sigma(2), 1 = sigma(3)$) gilt
$
product_(1 <= i < j <= n) (sigma(j) - sigma(i))/(j - i) = (2-3)/(2-1) dot (1-3)/(3-1) dot (1-2)/(3-2) = (-1)^3 = -1 = sgn(sigma)
$
Diese Eigenschaft kann man allgemein beweisen:
#bold[Lemma 7.8:] Seien $n in NN$ und $sigma in S_n$. Dann gilt
$
sgn(sigma) = product_(1 <= i < j <= n) (sigma(j)- sigma(i))/(j -i )
$
#italic[Beweis:]
$n = 1:$ Wegen der Definition von $sgn$ und der Definition des leeren Produktes folgt $1 = 1$.
$n > 1:$ Sei $sgn(sigma) = (-1)^k$, d.h. die Anzahl der Fehlstände ist $k$. Dann gilt
$
product_(1 <= i < j <= n) (sigma(j) - sigma(i)) = (-1)^k product_(1<= i < j <=n) (sigma(j) - sigma(i)) \
= (-1)^k product_(1 <= i < j <= n) (j -i)
$
Bei diesen letzten Gleichungen verwendet man, dass die beiden Produkte bis auf die Reihenfolge die gleichen Faktoren enthalten.
#endproof
#bold[Satz 7.9:] Seien $n in NN$ und $cal(T), sigma in S_n$. Dann gilt
$
sgn(cal(T) circ sigma) = sgn(cal(T)) dot sgn(sigma)
$
#italic[Beweis:] Wegen Lemma 7.8 gilt:
$
sgn(cal(T) circ sigma) = product_(1 <= i < j <= n) (cal(T)(sigma(j)) - cal(T)(sigma(i)))/(j - i) \
= underbrace(product_(1 <= i < j <= n) (cal(T)(sigma(j)) - cal(T)(sigma(i)))/(sigma(j) - sigma(i)), = sgn(cal(T)) space ?) underbrace(product_(1 <= i < j <= n) (sigma(j) - sigma(i))/(j-i), = sgn(sigma)) \
$
zu zeigen: ? (s.o.)
$
product_(1 <= i < j <= n) (cal(T)(sigma(j)) - cal(T)(sigma(i)))/(sigma(j) - sigma(i)) = limits(product_(1 <= i < j <= n))_(sigma(i)<sigma(j)) (cal(T)(sigma(j)) - cal(T)(sigma(i)))/(sigma(j) - sigma(i)) limits(product_(1 <= i < j <= n))_(sigma(i) > sigma(j)) (cal(T)(sigma(j)) - cal(T)(sigma(i)))/(sigma(j)- sigma(i)) \
= limits(product_(1 <= i < j <= n))_(sigma(i)<sigma(j)) (cal(T)(sigma(j)) - cal(T)(sigma(i)))/(sigma(j) - sigma(i)) limits(product_(1 <= j < i <= n))_(sigma(i) < sigma(j)) (cal(T)(sigma(j)) - cal(T)(sigma(i)))/(sigma(j)- sigma(i)) = limits(product_(1 <= i < j <= n))_(sigma(i)<sigma(j)) (cal(T)(sigma(j)) - cal(T)(sigma(i)))/(sigma(j) - sigma(i)) \
=^(star) product_(1<=i<j<=n) (cal(T)(j) - cal(T)(i))/(j - i) =^"Lemma 7.8" sgn(cal(T))
$
$star$: $sigma$ ist bijektiv, damit enthält das letzte Produkt bis auf die Reihenfolge die gleichen Faktoren.
#bold[Lemma 7.10:] Sei $n in NN$. Dann gilt
#box(width: 100%, inset: (left: 1cm, right: 1cm))[
1. Ist $cal(T) in S_n$ eine Tranposition, so gilt $sgn(cal(T)) = -1$
2. Ist $sigma in S_n$ mit $sigma = cal(T)_1 circ ... circ cal(T)_k$ mit Transpositionen $cal(T)_i in S_n$, so ist $sgn(sigma) = (-1)^k$
]
#italic[Beweis:]
zu 1: Sei $cal(T)$ die Transposition, die $k$ und $l$ mit $1<=k<l<=n$ vertauscht. Damit ist $l = k + j$ für ein $j >= 1$ und $cal(T)$ ist gegeben durch
$
cal(T) = [1 space space 2 space space k-1 space space overbrace(k+j, = l) space space k+1 space space ... space space overbrace(k+j-1, l-1) space space k space space overbrace(k+j+1, l+1) space space ... space space n]
$
Damit hat $cal(T)$ die Fehlstände
$
underbrace((k space.quad k+1)\, dots \, (k space.quad k+j) , j space.thin "Fehlstände"), underbrace((k+1 space.quad k+j)\, ...\, (k+j-1 space.quad k+j), j-1 space.thin "Fehlstände")
$
Insgesamt folgt: Anzahl der Fehlstände
$
j + j - 1 = 2 j - 1
$
$==> sgn(cal(T)) = (-1)^(2j-1) = -1$
zu 2) Folgt aus Satz 7.9.
#endproof
Wir brauchen noch:
#definition("7.11", "Charakteristik")[
Ist $R$ ein Ring mit $1 != 0$, so ist seine Charakteristik definiert durch
$
char (R) = cases(0"," space.quad "falls" n dot 1 != 0 space.quad forall n in NN, min{n in NN | n dot 1 = 0} space "sonst")
$
] <def>
Beispiel: $FF_2$ (vlg. Bsp. 2.8) gilt
$
&1+1 = 1 dot 1 + 1 dot 1 = underbrace((1+1),=0) dot 1 = 0 \
&1 = -1 space corres space "inverses Element bzgl. Addition"
$
Allgemein: "Bei einem Ring mit Charakteristik 2 darf man Vorzeichen ignorieren."
#bold[Korollar 7.12:] Sei $n in NN$. Für jede Permutation $sigma in S_n$ gilt
$
det (I_sigma) = det vec(e^top_(sigma(1)), dots.v, e^top_(sigma(n))) = cases(sgn(sigma) space.quad &"für" char (K) != 2, 1 &"für" char (K) = 2)
$
#italic[Beweis:]
Ist $sigma = cal(T)_1 circ dots circ cal(T)_k$, so kann man $I_sigma$ durch $k$ Zeilenvertauschungen aus $I_n$ erzeugen + D6.
#endproof
#bold[Satz 7.13:] Leibniz-Formel
Ist $K$ ein Körper und $n >= 1$, so gibt es genau eine Determinante $det: K^(n,n) -> K$. Dies ist für $A in K^(n,n)$ die Abbildung
$
det (A) = sum_(sigma in S_n) sgn(sigma) dot a_(1 sigma(1)) dot ... dot a_(n sigma(n)) wide (star)
$
Für $char (K) = 2$ sind die Faktoren $sgn(sigma)$ in den Summanden überflüssig.
#italic[Beweis:]
#bold[Eindeutigkeit:]
Dazu: Beweis, dass $(star)$ aus Axiomen folgt. Dafür: Darstellung jedes Zeilenvektors $a_i$ von $A$ als
$
a_i = a_(i 1) e^top_1 + a_(i 2) e^top_2 + ... + a_(i n) e^top_n
$
Aus D1 folgt:
$
det (A) &= det vec(a_1, dots.v, a_n) = sum_(j_1 = 1)^n a_(1 j_1) det vec(e_(j_1)^top, a_2, dots.v, a_n) \
&= sum_(j_1 = 1)^n a_(1 j_1) dot (sum_(j_2 = 1)^n a_(2 j_2) det vec(e_(j_1)^top, e_(j_2)^top, a_3, dots.v, a_n)) \
&= ... \
&= sum_(j_1 = 1)^n sum_(j_2 = 1)^n dots sum_(j_n = 1)^n a_(1 j_1) space a_(2 j_2) space a_(3 j_3) space ... space a_(n j_n) underbrace(det vec(e_(j_1)^top, e_(j_2)^top, dots.v, e_(j_n)^top), (1))
$
$(1)$: $sgn(sigma) = sgn([j_1 space.quad j_2 space.quad ... space.quad j_n])$
$
det vec(e_(1 j_1)^top, dots.v, e^top_(n j_n)) = cases(0 #h(3.5em) &exists k\,l in {1, ..., n} space j_k = j_l , sgn(sigma) &sigma = [j_1 space.quad ... space.quad j_n])
$
D1 - D3 sichern damit die Eindeutigkeit.
#bold[Existenz:] zu zeigen, dass $(star)$ die Axiome D1-D3 aus Def 7.1 erfüllt.
D1.1:
$
det vec(dots.v, a_i^' + a_i^'', dots.v) &= sum_(sigma in S_n) sgn(sigma) a_(1 sigma(1)) dots (a^'_(i sigma(i)) + a^''_(i sigma(i))) dots a_(n sigma(n)) \
&= sum_(sigma in S_1) sgn(sigma) a_(1 sigma(1)) dots a_(i sigma(i))^' dots a_(n sigma(n)) + sum_(sigma in S_n) sgn(sigma) a_(1 sigma(1)) dots a_(i sigma(i))^'' dots a_(n sigma(n)) \
&= det vec(dots.v, a_i^', dots.v) + det vec(dots.v, a_i^'', dots.v), "D1.2 kann man analog nachrechnen"
$
D2:
Angenommen in $A in K^(n,n)$ sind Zeilen $k$ und $l$ mit $k<l$ gleich. Ist $cal(T)$ die Transposition, die $K$ und $l$ vertauscht, so gilt $sgn(cal(T)) = -1$. Betrachte
$
A_n = {sigma in S_n | sgn(sigma) = 1}
$
Dann gilt für $sigma in S_n$ mit $sgn(sigma) = -1$ dass $sigma in A_n^C := {tilde(sigma) circ cal(T) | tilde(sigma) in S_n}$, denn
$
sgn(sigma circ cal(T)^(-1)) = 1 space "und" space sigma = underbrace(sigma circ cal(T)^(-1), in A_n) circ cal(T)
$
Dann ist
$
S_n = A_n union A_n^C space "und" space A_n sect A_n^C = emptyset
$
Daraus folgt:
$
det (A) &= sum_(sigma in A_n) a_(1 sigma(1)) op(dots) a_(n sigma(n)) - sum_(sigma in A_n^C) a_(1 sigma(1)) op(dots) a_(n sigma(n)) \
&= sum_(sigma in A_n) a_(1 sigma(1)) op(dots) a_(n sigma(n)) - sum_(sigma in A_n) a_(1 sigma(cal(T)(1))) op(dots) a_(n sigma(cal(T)(n)))
$
$a_l = a_k ==>$
$
overbrace(a_(1 sigma(1)), sigma(cal(T)(1)) = sigma(1)) op(dots) a_(k sigma(cal(T)(k))) op(dots) a_(l sigma(cal(T)(l))) op(dots) overbrace(a_(n sigma(n)), sigma(n) = sigma(cal(T)(n))) \
= a_(1 sigma(1)) op(dots) a_(k sigma(l)) op(dots) a_(l sigma(k)) op(dots) underbrace(a_(n sigma(cal(T)(n))), =a_(n sigma(n)))
$
Damit heben sich die Summanden in $(star)$ gegenseitig auf und es folgt $det (A) = 0$.
D3: Für $sigma in S_n$ gilt
$
delta_(1 sigma(1)) dot delta_(2 sigma(2)) op(dots) delta_(n sigma(n)) = cases(0 space.quad &"für" sigma != id, 1 &"für" sigma = id)
$
Damit folgt
$
det (I_n) = det (delta_(i j)) = sum_(sigma in S_n) sgn(sigma) delta_(1 sigma(1)) op(dots) delta_(n sigma(n)) = 1^n
$
#endproof
Berechnung von Determinanten?
Man kann sich überlegen, dass die Leibniz-Formel $n!$ Summanden hat $-->$ Komplexität der Berechnung? $corres$ Rechenaufwand ?? (?)
Beispiel: lösen von $A x = b$ mit $A in RR^(n,n)$, $n = 20$, $b in RR^n$ pro Operation ($corres$ Multiplikation, Addition, ...) 10^(-9) Sekunden
#boxedlist[
Cramersche Regel: $#sspace$
$
x_j = (det (A_j))/(det (A))
$
d.h. ersetze in $A_j$ die $j$-te Spalte von $A$ durch $b$.
Leibniz-Formel: $>= n dot n!$ Operationen
$n = 20$: $n dot n! approx 5 dot 10^19$ Operationen
$==>$ Rechenzeit von 1500 Jahren
][
Laplacescher Entwicklungssatz:
$
det (A) = sum (-1)^(i + j) a_(i j) det (A_(i j))
$
$A_(i j)$ $corres$ Streichen $i$-te Zeile, $j$-te Spalte
Operationen: $n dot 2^n$
$n = 20$: $n dot 2^n approx 21 000 000$
Rechenzeit: 0.021 Sekunden
][
Gauß-Verfahren
etwa $n^3$ Operationen (siehe numerische lineare Algebra)
$n = 20$: 8000 Operationen
Rechenzeit: 0.000008 Sekunden
]
|
|
https://github.com/0x1B05/nju_os | https://raw.githubusercontent.com/0x1B05/nju_os/main/lecture_notes/content/06_并发控制基础.typ | typst | #import "../template.typ": *
#pagebreak()
= 并发控制基础
== 互斥问题
=== 并发编程:从入门到放弃
人类是 sequential creature
- 编译优化 + weak memory model 导致难以理解的并发执行
- 有多难理解呢?
- [ Verifying sequential consistency 是 NP-完全问题
](https://epubs.siam.org/doi/10.1137/S0097539794279614)
人类是 (不轻言放弃的) sequential creature
- 有问题,就会试着去解决
- 手段:“回退到” 顺序执行
- 标记若干块代码,使得这些代码一定能按某个顺序执行
- 例如,我们可以安全地在块里记录执行的顺序
=== 回退到顺序执行:互斥
插入 “神秘代码”,使得所有其他 “神秘代码” 都不能并发, 由 “神秘代码”
领导不会并发的代码 (例如 pure functions) 执行:
```c
void Tsum() {
stop_the_world();
// 临界区 critical section
sum++;
resume_the_world();
}
```
Stop the world 真的是可能的
- Java 有 “stop the world GC”
- 单个处理器可以关闭中断
- 多个处理器也可以发送核间中断
>
因为需要并发的代码总是占少数的,不需要并发的代码并发执行就可以提高性能(加速比)。如果并发的代码比例大,那加速比就会小。
=== 失败的尝试
```c
int locked = UNLOCK;
void critical_section() {
retry:
if (locked != UNLOCK) {
goto retry;
}
locked = LOCK;
// critical section
locked = UNLOCK;
}
```
和 “山寨支付宝” 完全一样的错误: 并发程序不能保证 load + store 的原子性
=== 更严肃地尝试:确定假设、设计算法
假设:内存的读/写可以保证顺序、原子完成
- `val = atomic_load(ptr)`
- 看一眼某个地方的字条 (只能看到瞬间的字)
- 刚看完就可能被改掉
- `atomic_store(ptr, val)`
- 对应往某个地方 “贴一张纸条” (必须闭眼盲贴)
- 贴完一瞬间就可能被别人覆盖
对应于 model checker
- 每一行可以执行一次全局变量读或写
- 每个操作执行之后都发生 `sys_sched()`
==== 正确性不明的奇怪尝试 (Peterson 算法)
A 和 B 争用厕所的包厢
- 想进入包厢之前,A/B 都首先举起自己的旗子
- A 往厕所门上贴上 “B 正在使用” 的标签
- B 往厕所门上贴上 “A 正在使用” 的标签
- 然后,如果对方举着旗,且门上的名字是对方,等待
- 否则可以进入包厢
- 出包厢后,放下自己的旗子 (完全不管门上的标签)
===== 习题:证明 Peterson 算法正确,或给出反例
进入临界区的情况
- 如果只有一个人举旗,他就可以直接进入
- 如果两个人同时举旗,由厕所门上的标签决定谁进
- 手快 🈶️ (被另一个人的标签覆盖)、手慢 🈚
一些具体的细节情况
- A 看到 B 没有举旗
- B 一定不在临界区
- 或者 B 想进但还没来得及把 “A 正在使用” 贴在门上
- A 看到 B 举旗子
- A 一定已经把旗子举起来了
- `(!@^#&!%^(&^!@%#`
===== 绕来绕去很容易有错漏的情况
Prove by brute-force
枚举状态机的全部状态 (PC1,PC2,x,y,turn)
但手写还是很容易错啊——可执行的状态机模型有用了!
```c
void TA() { while (1) {
/* ❶ */ x = 1;
/* ❷ */ turn = B;
/* ❸ */ while (y && turn == B) ;
/* ❹ */ x = 0; } }
void TB() { while (1) {
/* ① */ y = 1;
/* ② */ turn = A;
/* ③ */ while (x && turn == A) ;
/* ④ */ y = 0; } }
```
spin.py
```py
def T1():
while heap.lock != '✅':
sys_sched()
sys_sched()
heap.lock = '❌'
sys_write('❶')
def T2():
while heap.lock != '✅':
sys_sched()
sys_sched()
heap.lock = '❌'
sys_write('❷')
def main():
heap.lock = '✅'
sys_spawn(T1)
sys_spawn(T2)
= Outputs:
= ❶❷
= ❷❶
```
== 模型、模型检验与现实
=== “Push-button” Verification 🎖
我们 (在完全不理解算法的前提下) 证明了 Sequential 内存模型下 Peterson's Protocol
的 Safety。它能够实现互斥。
并发编程比大家想象得困难
感受一下 [ Dekker's Algorithm
](https://series1.github.io/blog/dekkers-algorithm/) [ “Myths about the mutual
exclusion problem” (IPL, 1981)
](https://zoo.cs.yale.edu/classes/cs323/doc/Peterson.pdf)
=== 自动遍历状态空间的乐趣
可以帮助我们快速回答更多问题
- 如果结束后把门上的字条撕掉,算法还正确吗?
- 在放下旗子之前撕
- 在放下旗子之后撕
- 如果先贴标签再举旗,算法还正确吗?
- 我们有两个 “查看” 的操作
- 看对方的旗有没有举起来
- 看门上的贴纸是不是自己
- 这两个操作的顺序影响算法的正确性吗?
- 是否存在 “两个人谁都无法进入临界区” (liveness)、“对某一方不公平” (fairness)
等行为?
- 都转换成图 (状态空间) 上的遍历问题了!
#tip("Tip")[
- 完全理解非常困难,所以要借助model checker.
- 有合法状态以及非法状态,如果存在合法状态->非法状态的一条通路,寄!
- 不存在死锁应该怎么在状态图上表示?
]
=== Model Checker 和自动化
电脑为什么叫 “电脑”
- 就是因为它能替代部分人类的思维活动
回忆:每个班上都有一个笔记和草稿纸都工工整整的 Ta
- 老师:布置作业画状态图
- Ta:认认真真默默画完
- 工整的笔记可以启发思维
- 但 scale out 非常困难
- 我:烦死了!劳资不干了!玩游戏去了!
- 计算思维:写个程序 (model checker) 来辅助
- 任何机械的思维活动都可以用计算机替代
- AI 还可以替代启发式/经验式的决策
=== 从模型回到现实……
回到我们的假设 (体现在模型)
- Atomic load & store
- 读/写单个全局变量是 “原子不可分割” 的
- 但这个假设在现代多处理器上并不成立
- 所以*实际上按照模型直接写 Peterson 算法应该是错的?*
“实现正确的 Peterson 算法” 是合理需求,它一定能实现
- Compiler barrier/volatile 保证不被优化的前提下
- 处理器提供特殊指令保证可见性
- 编译器提供 `__sync_synchronize()` 函数
- x86: `mfence;` ARM: `dmb ish;` RISC-V: `fence rw, rw`
- 同时含有一个 compiler barrier
#tip("Tip")[
`x = 1`,`y=2`在正常情况下就有可能被编译器优化, 乱序执行。而如果先贴名字再举旗子的话,peterson算法是错误的。
]
=== 🌶️ 维持实现到模型的对应
==== Peterson 算法:C 代码实现演示
peterson.c
```c
#include "thread.h"
#define A 1
#define B 2
#define BARRIER __sync_synchronize()
atomic_int nested;
atomic_long count;
void critical_section() {
long cnt = atomic_fetch_add(&count, 1);
int i = atomic_fetch_add(&nested, 1) + 1;
if (i != 1) {
printf("%d threads in the critical section @ count=%ld\n", i, cnt);
assert(0);
}
atomic_fetch_add(&nested, -1);
}
// x, y代表举旗子, turn代表贴名字
int volatile x = 0, y = 0, turn;
void TA() {
while (1) {
x = 1; BARRIER;
turn = B; BARRIER; // <- this is critcal for x86
while (1) {
if (!y) break; BARRIER;
if (turn != B) break; BARRIER;
}
critical_section();
x = 0; BARRIER;
}
}
void TB() {
while (1) {
y = 1; BARRIER;
turn = A; BARRIER;
while (1) {
if (!x) break; BARRIER;
if (turn != A) break; BARRIER;
}
critical_section();
y = 0; BARRIER;
}
}
int main() {
create(TA);
create(TB);
}
```
如果peterson错了, 例如把barrier注释掉。
```
TA TB
lock()
t=++n(atomic)
t=++n(此时t=2)
n--(atomic)
unlock()
```
可以看到很多次之后才会出现错误。
如果把`barrier`改成: `#define BARRIER asm volatile ("" ::: "memory")`
也是错误的,但是时间更久,这个barrier更强.
`#define BARRIER asm volatile ("mfence" ::: "memory")`
`#define BARRIER __sync_synchronize()`
- 一些有趣的问题
- Compiler barrier 能够用吗?
- 哪些地方的 barrier 是不可少的?
- 测试只能证明 “有问题”,不能证明 “没问题”
编译器到底做了什么?
- 推荐:#link("http://godbolt.org/")[ godbolt.org ],你不用装那些 cross compiler 了
- 你甚至可以看到 compiler barrier 是如何在优化中传递的
- 再一次:自动化 & 可视化的意义
- 不懂可以把代码直接扔给 ChatGPT
== 原子指令
=== 并发编程困难的解决
写一个正确的无锁的并发代码非常非常困难。(需要对编译器,处理器,编程语言非常非常了解).
普通的变量读写在编译器 + 处理器的双重优化下行为变得复杂。通过原子的`load()`,`store()`来构造`lock()`和`unlock()`已经完全行不通。
```c
retry:
if (locked != UNLOCK) {
goto retry;
}
locked = LOCK;
```
解决方法:编译器和硬件共同提供不可优化、不可打断的指令
- “原子指令” + compiler barrier
=== 实现正确的求和
```c
for (int i = 0; i < N; i++)
asm volatile("lock incq %0" : "+m"(sum));
```
#tip("Tip")[
如果把`lock`去掉,那就是上一节的`sum`. 加上这个`lock`之后,显著地慢了。
]
```
> gcc -O2 sum-atomic.c && time ./a.out
sum = 200000000
./a.out 3.80s user 0.00s system 199% cpu 1.910 total
> gcc -O2 sum-atomic.c && time ./a.out
sum = 108010081
./a.out 2.49s user 0.00s system 199% cpu 1.252 total
```
“Bus lock”(总线锁)——从 80386 开始引入 (bus control signal)
#image("images/2024-03-18-12-36-24.png")
`lock`的实现,就是在引脚上面加上一个`lock`的信号线(低电平有效). 当执行`lock`的时候,该cpu就有了内存的独占访问权(别的CPU要访问内存都不行,
直到再次被拉高)。
=== 🌶️ 编译器和硬件的协作
Acquire/release semantics
- 对于一对配对的 release-acquire
- (逻辑上) release 之前的 store 都对 acquire 之后的 load 可见
- [ Making Sense of Acquire-Release Semantics
](https://davekilian.com/acquire-release.html)
- `std::atomic`
- `std::memory_order_acquire`: guarantees that subsequent loads are not moved
before the current load or any preceding loads.
- `std::memory_order_release`: preceding stores are not moved past the current
store or any subsequent stores.
- `x.load()`/`x.store()` 会根据 [ memory order
](https://en.cppreference.com/w/cpp/atomic/memory_order) 插入 `fence`
- `x.fetch_add()` 将会保证 `cst` (sequentially consistent)
- 去 #link("https://godbolt.org/")[ godbolt ] 上试一下吧
|
|
https://github.com/VisualFP/docs | https://raw.githubusercontent.com/VisualFP/docs/main/SA/design_concept/content/introduction/tool_research/reddit_suggestion_visual_fp.typ | typst | = Reddit Suggestion for visual pure functional programming
The Reddit user 'Jameshfisher' suggested a style of pure visual programming
@reddit_visual_fp. It is only theoretical and, therefore, not an existing
tool. A picture of the suggestion is shown in @screenshot_reddit_visual_fp.
#figure(
image("../../../static/reddit_suggestion_visual_fp.png", width: 80%),
caption: [
Suggestion for visual pure function programming by Reddit user Jameshfisher
Source: Adapted from @reddit_visual_fp
]
)<screenshot_reddit_visual_fp>
But the proposed concept is very intriguing. Instead of drawing a function from
the outside, functions are drawn from the inside.
A function's input is displayed on the top, and the output on the bottom.
The arrows show how the output is composed of other expressions.
Out of all the researched tools, this suggestion shows functional
programming concepts best. |
|
https://github.com/abhinav12k/Typster | https://raw.githubusercontent.com/abhinav12k/Typster/main/README.md | markdown | # ⌨️ Typster
[](https://www.codacy.com/gh/abhinav12k/Typster/dashboard?utm_source=github.com&utm_medium=referral&utm_content=abhinav12k/Typster&utm_campaign=Badge_Grade)
[](https://kotlinlang.org)
[](https://developer.android.com/jetpack/compose/setup)
[](https://github.com/abhinav12k/Typster/releases/download/v1.0.0/Typster-1.0.0.msi)
[](https://github.com/abhinav12k/Typster/releases/download/v1.0.0/typster_1.0.0_amd64.deb)

[](https://youtu.be/GJDn7zIaAqk)
[](https://hits.sh/github.com/abhinav12k/Typster/)

<img src="preview/typster.png"/>
> Typster is a simple typing game built using Desktop Compose. The game allows you to test your typing skills by typing a given text as fast and accurately as possible. You can also customize the text to your liking.
## 📺 Preview
https://user-images.githubusercontent.com/51455561/227321320-b66ebcbd-8856-4832-a78f-9f899e8ea246.mp4
## 🏃 Run
- Clone the repo and run `./gradlew run`
## 💡 Inspiration
- Inspired by the Typing game of Phoboslab
## 🛠 Built With
- [Kotlin](https://kotlinlang.org/) - A modern day concise and cross platform language
- [Desktop Compose](https://www.jetbrains.com/lp/compose-desktop/) - A declarative UI framework for building modern, responsive desktop applications using Kotlin.
- [OpenRndr Math](https://openrndr.org/) - Math functions and classes required for 2D plane simulation
## ✍️ Author
👤 **abhinav12k**
- Website: <a href="https://abhinav12k.github.io/" target="_blank">abhinav12k</a>
- LinkedIn: <a href="https://www.linkedin.com/in/abhinav12k/">abhinav12k</a>
- Email: <EMAIL>
Feel free to ping me 😉
## 🤝 Contributing
Contributions are what make the open source community such an amazing place to be learn, inspire, and create. Any contributions you make are **greatly appreciated**.
1. Open an issue first to discuss what you would like to change.
2. Fork the Project
3. Create your feature branch (`git checkout -b feature/amazing-feature`)
4. Commit your changes (`git commit -m 'Add some amazing feature'`)
5. Push to the branch (`git push origin feature/amazing-feature`)
6. Open a pull request
## ❤ Show your support
Give a ⭐️ if this project helped you!
## ☑️ TODO
- [ ] Scoreboard
- [x] WPM and accuracy calculator
- [ ] Set difficulty levels
- [ ] Typing mistakes sound and design
- [ ] Other alphabets and numbers support
## © 2023 Abhinav. All rights reserved.
|
|
https://github.com/yhtq/Notes | https://raw.githubusercontent.com/yhtq/Notes/main/代数学二/作业/hw8.typ | typst | #import "../../template.typ": *
#import "@preview/commute:0.2.0": node, arr, commutative-diagram
#show: note.with(
title: "作业8",
author: "YHTQ",
date: none,
logo: none,
withOutlined : false,
withTitle :false,
)
(应交时间为4月23日)
#let Supp = math.op("Supp")
#set heading(numbering: none)
= p67
== 1
将 $phi$ 分解为 $i compose pi$,其中 $pi: A -> A quo ker phi$ 是商同态,$i: A quo ker phi tilde.eq im phi -> B$ 是嵌入,只需要分别验证 $i^*, pi^*$ 都是闭映射即可\
事实上,$pi$ 作为商映射,根据对应原理成为闭映射是容易的,只需验证 $i$ 是闭映射\
任取 $V(alpha) subset Spec(B)$ 是闭集,由于 $phi$ 是整同态, $i$ 当然也是,而 $i$ 是嵌入,利用熟知的结论可得 $i^*$ 是满射,前面的习题证明了 $overline(i^*(V(alpha))) = V(Inv(i)(alpha))$,只需证明 $V(Inv(i)(alpha)) subset i^*(V(alpha))$ 即可\
事实上:
$
p_A in V(Inv(i)(alpha)) <=> Inv(i)(alpha) subset p_A\
$
既然 $B$ 在 $im phi$ 上整,自然有 $B quo alpha$ 在 $im phi quo Inv(i)(alpha)$ 上整,因此:
$
Inv(i)(alpha) subset p_A => overline(p_A) in Spec(im phi quo Inv(i)(alpha)) => exists overline(p_B) in Spec(B quo alpha), overline(Inv(i))(overline(p_B)) = overline(p_A)
$
其中当然有 $p_B in V(alpha)$ 且 $i^*(p_B) = p_A => p_A in i^*(V(alpha))$,得证
== 2
#align(center)[#commutative-diagram(
node((0, 0), $A$, 1),
node((0, 1), $B$, 2),
node((1, 0), $A quo (ker f := p_A)$, 3),
node((1, 1), $B quo p_B$, 4),
arr(1, 2, $$, inj_str),
arr(1, 3, $$),
arr(2, 4, $$),
arr(3, 4, $$, inj_str),
node((3, -1), $Omega$, 5),
node((2, 0), $k_(A quo p_A)$, 6),
node((2, 1), $k_(B quo p_B)$, 7),
arr(1, 5, $f$),
arr(3, 5,$exists f_1$),
arr(3, 6, $$),
arr(4, 7, $$),
arr(6, 7, $$, inj_str),
arr(6, 5, $exists f_2$),
arr(7, 5, $exists f'$)
)]
其中:
- $p_A = ker f$ 当然是 $A$ 的素理想,因此存在 $p_B in Spec(B)$ 使得 $p_B sect A = p_A$ 并有第二层的交换图表和自然的嵌入 $f_1$
- $A quo p_A, B quo p_B$ 都是整环,$k_(A quo p_A), k_(B quo p_B)$ 是其上的分式域,$f_2$ 利用环到域的同态延拓到分式环上产生
- 利用 $Omega$ 是代数闭域和域中的同态延拓定理,$f_2$ 可被延拓到 $f'$
由于整个交换图表成立,不难验证 $(B -> B quo p_B -> k_(B quo p_B) -> Omega)$ 在 $A$ 上的限制就是 $f$,证毕
== 3
任取 $b' tensorProduct 1 in B' tensorProduct C$(当然 $B' tensorProduct C$ 中元素均形如 $b' tensorProduct c = c b' tensorProduct 1$,不妨就设为 $b' tensorProduct 1$),由于 $B'$ 在 $B$ 上整,故存在首一多项式使得:
$
b'^n + b_1 b'^(n-1) + ... + b_n = 0, b_n in B
$
将有:
$
(b' tensorProduct 1)^n + (b_1 tensorProduct 1) (b' tensorProduct 1)^(n-1) + ... + (b_n tensorProduct 1) = 0 tensorProduct 1 = 0
$
这就产生了一个 $b' tensorProduct 1$ 的首一零化多项式,系数均在 $B tensorProduct C$ 中,因此 $B tensorProduct C$ 在 $B' tensorProduct C$ 上整,得证
== 5
=== i)
设 $Inv(x) in B$ 在 $A$ 上的零化多项式为:
$
x^(-n) + a_1 x^(-n+1) + ... + a_n = 0, a_n in A
$
从而有:
$
x^(-1) + a_1 + ... + a_n x^(n-1) = 0
$
上式除第一项外都在 $A$ 中,自然 $Inv(x)$ 也在,证毕
=== ii)
由整性 $phi^*: Spec(B) -> Spec(A)$ 将诱导 $max(B) -> max(A)$ 上的满射,因此:
$
sect max(B) sect A = (sect_(m_B in max(B)) m_B) sect A = sect_(m_B in max(B)) m_B sect A \
= sect_(m_B in max(B)) phi^*(m_B) = sect_(m_A in max(A)) m_A = sect max(A)
$
== 7
任取 $x in B - A$,则:
- $x + A subset B - A$ ,否则不难得到 $x in A$,矛盾!
- $x(x + A) = x^2 + A x subset B - A$,既然 $B-A$ 对乘法封闭
- ...
- 以此类推,将有 $x^(n-1) + sum_(i=0)^(n-1) A x^i subset B - A$ 不可能为零,自然 $x$ 不可能存在首一零化多项式,证毕
== 8
=== i)
取 $B$ 的分式域的代数闭包 $Omega$,并设 $f, g$ 在 $Omega$ 中被分解为:
$
f = product_(i=1)^n (x - a_i), g = product_(j=1)^m (x - b_j)
$
注意到 $f g in C[x]$,因此 $a_i, b_i$ 都在 $C$ 上整,故 $f, g$ 的系数(它们都含于 $C[a_i], C[b_i]$)在 $C$ 上整。然而这些系数都在 $B$ 之中,且 $C$ 在 $B$ 中已经整闭,故当然系数都在 $C$ 中,得证
=== ii)
设任取 $B$ 中素理想 $p$,则当然有:
$
A quo (p sect A) subset C quo (p sect C) subset B quo p
$
且都是整环,由上题结论得 $overline(f), overline(g)$ 的所有系数落在 $A quo (p sect A)$ 的整闭包中,进而在其上整。\
#lemmaLinear[][
设 $x in B$ 且任取素理想 $p in Spec(B)$ 均有 $overline(x) in B quo p$ 在 $A quo (p sect A)$ 上整,则 $x$ 在 $A$ 上整
]
#proof[
令:
$
S = {f(x) | f in A[x] "首一"} subset B
$
它将是 $B$ 的乘性子集,注意到 $Inv(S) B$ 一定有素理想,因此 $B$ 中一定有与 $S$ 不交的素理想 $p$,然而条件给出:
$
exists a_i, x^n + (a_i + p) x^(n-1) + ... + (a_n + p) in p\
x^n + a_i x^(n-1) + ... + a_n in p
$
当然与假设矛盾
]
由引理,结论立即成立
== 9
设 $f in B[x]$ 在 $A[x]$ 上整,则:
$
f^n + a_(1) f^(n-1) + ... + a_(n) = 0, a_(n) in A[x]\
$
设 $f = x^r + f'$,则:
$
(x^r + f')^n + a_(1) (x^r + f')^(n-1) + ... + a_(n) = 0\
f'^n + a'_(1) f'^(n-1) + ... + a'_(n) = 0\
-f'(f'^(n-1) + a'_(1) f'^(n-2) + ... + a'_(n-1)) = a'_(n)
$
当 $r$ 足够大时,$a'_n$ 的首项为 $x^(r n)$ 因此首一,利用上题结论可得 $f$ 的系数在 $A$ 上都是整的,也即 $f in C[x]$,证毕
== 10
=== i)
==== a $=>$ b
只需证明设 $p_1 subset p_2, p_1 = f^*(q_1)$ 则存在 $q_2 supset q_1$ 使得 $p_2 = f^*(q_2)$\
前面的习题证明了 $overline(f^*(V(q_1))) = V(Inv(f)(q_1))$,因此 $f$ 是闭映射表明:
$
f^*(V(q_1)) = V(Inv(f)(q_1)) = V(p_1)
$
由于 $p_2 in V(p_1)$,当然有 $exists q_2 in V(q_1), f^*(q_2) = p_1$,得证
==== b $=>$ c
任取 $p' A quo p in Spec(A quo p)$,则 $p'$ 是包含 $p$ 的素理想,由 going up 性质知存在 $q' supset q$ 使得:
$
f^*(q') = p'
$
观察交换图表:
#align(center)[#commutative-diagram(
node((0, 0), $A$, 1),
node((0, 1), $B$, 2),
node((1, 0), $A quo p$, 3),
node((1, 1), $B quo q$, 4),
arr(1, 2, $f$),
arr(1, 3, $$),
arr(2, 4, $$),
arr(3, 4, $overline(f)$),)]
将有:
$
Inv(f)(Inv((B -> B quo q))(q' B quo q)) = Inv(f)(q') = p'\
p' = Inv(f)(Inv((B -> B quo q))(q' B quo q)) = Inv((A -> A quo p))(overline(f^(-1))(q' A quo p)) \
p' A quo p = overline(f^(-1))(q' A quo p)
$
证毕
==== c $=>$ b
只需证明设 $p_1 subset p_2, p_1 = f^*(q_1)$ 则存在 $q_2 supset q_1$ 使得 $p_2 = f^*(q_2)$\
在满射 $overline(f)^*: Spec(B quo q_1) -> Spec(A quo p_1)$ 中,取 $overline(f)^*(q_2) = p_2$,由类似上面的过程可以证明 $f^*(q_2) = p_2$
=== ii)
==== a $=>$ c
利用:
$
B_q = union_(x in B - q) B_x = directLimit B_x\
f^*(Spec(B_q)) = sect_(x in B - q) f^*(Spec(B_x))
$
然而 $Spec(B_x)$ 是($Spec(B)$ 中)包含 $q$ 的开集,以及 $f^*$ 是开映射,因此 $f^*(Spec(B_x))$ 是包含 $f^*(q) = p$ 的开集 $Spec(A) - V(alpha), alpha subset.not p$,显然 $V(alpha)$ 中没有含于 $p$ 的理想,因此前式一定包含 $Spec(A_p)$,证毕
==== b $<=>$ c
与之前类似,可以证明 $Spec(B_q) -> Spec(A_p)$ 是满射当且仅当 $forall p' in Spec(A), p' subset p => exists q' subset q, f^*(p') = q'$,由 $p, q$ 的任意性这就是 going down 性质
== 11
验证上题中的 c',设 $p = Inv(f)(q)$ ,考虑诱导的 $f': A_p -> B_q$ 也是平坦同态。事实上,注意到 $A -> B -> B_q$ 由传递性平坦,而:
$
Inv((A - p)) (A -> B -> B_q) = A_p -> Inv((A - p)) B_q = A_p -> B_q = f'
$
由局部化函子的正合性也是平坦同态\
熟知局部环之间的平坦同态一定忠实平坦,继而 $Spec(B_q) -> Spec(A_p)$ 是满射,得证
== 12
任取 $x in A$ ,设:
$
f(t) = product_(sigma in G) (t - sigma(x))
$
不难验证 $f(x) = 0$ 且任取 $sigma in G, sigma(f) = f$,因此 $f$ 的系数都在 $A^G$ 之中,这就是所求的首一零化多项式
有交换图表:
#align(center)[#commutative-diagram(
node((0, 0), $A$, 1),
node((0, 1), $A$, 2),
node((1, 0), $Inv(S) A$, 3),
node((1, 1), $Inv(S) A$, 4),
arr(1, 2, $sigma$),
arr(1, 3, $$),
arr(2, 4, $$),
arr(3, 4, $sigma'$),)]
其中 $sigma'$ 来自于 $A -> A -> Inv(S) A$ 由局部化产生的延拓,为此验证:
$
(A -> A -> Inv(S) A)(S) = (A -> Inv(S) A)(sigma(S)) subset (A -> Inv(S) A)(S) subset U(Inv(S) A)
$
因此延拓确实存在\
注意到 $S^G$ 当然也满足 $sigma(S^G) = S^G$ 因此有:
#align(center)[#commutative-diagram(
node((0, 0), $A$, 1),
node((0, 1), $A$, 2),
node((1, 0), $Inv(S^G) A$, 3),
node((1, 1), $Inv(S^G) A$, 4),
node((2, 0), $Inv(S) A$, 5),
node((2, 1), $Inv(S) A$, 6),
arr(1, 2, $sigma$),
arr(1, 3, $$),
arr(2, 4, $$),
arr(3, 4, $sigma''$),
arr(3, 5, $$),
arr(4, 6, $$),
arr(5, 6, $sigma'$),
)]
此外,不难验证:
$
(sigma'' compose (A -> Inv(S^G) A))|_(A^G) = ((A -> Inv(S^G) A) compose sigma)|_(A^G) = A^G -> Inv(S^G) A^G
$
换言之,$sigma''|_(Inv(S^G) A^G)$ 是 $(Inv(S^G)) A^G$ 上的自同态,且有:
#align(center)[#commutative-diagram(
node((0, 0), $A^G$, 1),
node((0, 1), $A^G$, 2),
node((1, 0), $Inv(S^G) A^G$, 3),
node((1, 1), $Inv(S^G) A^G$, 4),
arr(1, 2, $id$),
arr(1, 3, $$),
arr(2, 4, $$),
arr(3, 4, $sigma''|_(Inv(S_G) A^G)$),)]
由局部化延拓的唯一性知 $sigma''|_(Inv(S_G) A^G) = id$\
类似也可以证明 $sigma'|_(Inv(S) A^G) = id$,由 $sigma$ 的任意性当然就有:
$
im((Inv(S^G)) A^G -> Inv(S) A) subset (Inv(S) A)^G
$
反过来也可以证明:
$
//sigma'|_((Inv(S) A)^G) = id => sigma''|_(Inv(((Inv(S^G)) A^G -> Inv(S) A)) (Inv(S) A)^G) = id
sigma'|_((Inv(S) A)^G) = id => sigma|_(Inv((A-> Inv(S) A)) ((Inv(S) A)^G)) = id
$
由任意性可知:
$
(Inv((A-> Inv(S) A)) ((Inv(S) A)^G)) subset A^G \
=> (Inv(S) A)^G subset Inv(S) A^G = im((Inv(S^G)) A^G -> Inv(S) A)
$
因此 $(Inv(S^G)) A^G -> (Inv(S) A)^G$ 构成满射,只需证明它也是单射。\
为此,设 $a'/s' in (Inv(S^G)) A^G$ 在 $Inv(S) A$ 中为零,即:
$
exists s in S, a' s = 0
$
立刻有:
$
a' product_(sigma in G) sigma(s) = 0
$
而 $product_(sigma in G) sigma(s) in S'$,可得 $a'/s' = 0$,证毕
== 13
任取 $p_1, p_2 in P, x in p_1$,注意到:
$
product_(sigma in G) sigma(x) in A^G sect p_1 = p subset p_2
$
由素理想定义存在某个 $sigma$ 使得 $sigma(x) in p_2$,因此:
$
union_(sigma in G) sigma(p_1) supset p_2
$
注意到 $p_2$ 是素理想,由 prime avoidance lemma 知存在 $sigma in G$ 使得 $sigma(p_1) supset p_2$\
为了证明 $sigma(p_1) = p_2$,注意到:
$
sigma(p_1) sect A^G = sigma(p_1 sect Inv(sigma)(A^G)) = sigma(p_1 sect A^G) = p = p_2 sect A^G
$
结合 $A$ 在 $A^G$ 上整以及 $sigma(p_1) supset p_2$ 知它们取等,证毕
== 14
为了证明 $sigma(B) = B$,首先 $A = sigma(A) subset sigma(B)$,断言:
- $sigma(B)$ 当然在 $L$ 中整闭,否则设 $x in L - sigma(B)$ 使得:
$
x^n + sigma(b_1) x^(n-1) + ... + sigma(b_n) = 0\
(Inv(sigma)(x))^n + b_1 (Inv(sigma)(x))^(n-1) + ... + b_n = 0
$
由 $B$ 整闭知 $Inv(sigma)(x) in B, x in sigma(B)$,矛盾!
- $sigma(B)$ 在 $A$ 上整,因此任取 $sigma(x) in sigma(B)$,由 $B$ 的整性存在:
$
x^n + a_1 x^(n-1) + ... + a_n = 0\
sigma(x)^n + sigma(a_1) sigma(x)^(n-1) + ... + sigma(a_n) = 0\
sigma(x)^n + a_1 sigma(x)^(n-1) + ... + a_n = 0\
$
当然就表明 $sigma(x)$ 在 $A$ 上整\
由整闭包的唯一性知 $sigma(B) = B$
对于第二个命题,首先当然有 $A subset B^G$,其次由域论知识得:
$
B^G = B sect L^G = B sect K subset K
$
并且 $B^G$ 当然在 $A$ 上整,由 $A$ 的整闭性知 $B^G subset A$,证毕
== 15
- 设 $L quo K$ 是可分扩张,则只需要取其正规闭包 $L'$,对 $L' quo K$ 利用上题结论立得:
$
B^(Gal(L' quo K)) = A
$
再利用之前的结论即可得到所求有限性
- 设 $L quo K$ 是纯不可分扩张,设 $q in Spec(B), p in Spec(A)$ 满足 $q sect A = p$\
注意到 $B$ 中任意元素都是纯不可分元,其最小多项式形如:
$
x^(r^n) - a = 0, a in K, r = char(K)
$
结合 $B$ 在 $A$ 上整,$A$ 在分式域中整闭,可得上式中 $a in A$\
下设 $x in q$,则:
$
x^(r^n) = a in q sect A = p
$
令 $q_p = {x in B | exists n in NN, x^(r^n) in p}$,往证 $q_p = q$
- 首先,容易验证 $q'$ 是素理想(乘法是简单的,加法只需注意到 $(x + y)^(r^n) = x^(r^n) + y^(r^n)$)
- 其次,往证若 $x^(r^n) in p$,则其最小多项式形如 $x^(r^m) - a, a in p$\
事实上,首先由最小性知 $m <= n$,继而:
$
x^(r^n) = (x^(r^m))^(r^(n-m)) in p
$
由于 $p$ 是素理想,当然有 $x^(r^m) in sqrt(p) = p$,得证
- 进一步,断言它是素理想,因为设 $x y in q$,分别设三个最小多项式:
$
x^(r^n) = a_1 in A\
y^(r^m) = a_2 in A\
(x y)^(r^(t)) = a in p
$
不妨设 $m <= n$,继而:
$
(x y)^(r^n) = x^(r^n) (y^(r^m))^(r^(n - m)) = a_1 a_2^(r^(n-m)) in A
$
由最小性,$a_1 a_2^(r^(n-m))$ 一定是 $a$ 的次幂,进而 $a_1 a_2^(r^(n-m)) in p$,结合素理想定义一定有 $a_1 in p or a_2 in p$,得证
- 最后,$q subset q_p$ 是显然的,而 $q sect A = p, q_p sect A = sqrt(p) = p$,由 $B$ 在 $A$ 上整立得 $q = q_p$
注意到以上构造对任何素理想都成立,因此 $Spec(B) -> Spec(A)$ 是双射\
- 一般的,设 $L' subset L$ 是 $K$ 的可分闭包(此时 $L quo L'$ 是纯不可分扩张),$B'$ 是 $A$ 在 $L'$ 中的整闭包,$B$ 是 $B'$ 在 $L$ 中的整闭包(由传递性也是 $A$ 的整闭包),任取 $q in Spec(A)$,若 $p in Spec(B)$ 使得 $p sect A = q$,则:
$
q = (p sect B') sect A
$
由可分的情形,这样的 $p sect B'$ 至多只能有有限个,而对每个 $p sect B'$ 由纯不可分的情形将可以唯一确定一个 $p$,因此结论成立
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.