Exercise 8

Added Exercise 8 to repository
This commit is contained in:
2025-04-21 19:08:07 +02:00
parent c71d2e026f
commit 950098d35e
8 changed files with 432 additions and 11 deletions

View File

@@ -0,0 +1,122 @@
#+title: Task 4: Dual Numbers
#+author: JirR02
* Dual Numbers
:PROPERTIES:
:CUSTOM_ID: dual-numbers
:END:
In this task, you are required to implement a basic version of /dual
number/. Dual numbers are conceptually similar to complex number.
A dual numbers \(n\) is of the following form:
\[
z = a + \epsilon b
\]
with the following identity:
\[
\epsilon ^2 = 0
\]
Adding two dual numbers is done component-wise:
\[
(a + \epsilon b) + (c + \epsilon d) + (a+c) + \epsilon (b + d)
\]
Subtracting two dual numbers is also done component-wise:
\[
(a + \epsilon b) - (c + \epsilon d) = (a + \epsilon b) + (-c - \epsilon d) = (a - c) + \epsilon(b - d)
\]
Using the identity above, multiplying two dual numbers gives
\[
(a + \epsilon b)(c + \epsilon d) = ac + \epsilon(ad + bc)
\]
** Tasks
:PROPERTIES:
:CUSTOM_ID: tasks
:END:
You are required to extend the provided implementation of dual numbers
by adding the implementation for various arithmetic operators in
=DualNumber.cpp=.
*** Task 1: Addition operator
:PROPERTIES:
:CUSTOM_ID: task-1-addition-operator
:END:
Implement the addition operator
#+begin_src shell
DualNumber operator+(const DualNumber& dn1, const DualNumber& dn2)
#+end_src
in file =DualNumber.cpp=.
*** Task 2: Subtraction operator
:PROPERTIES:
:CUSTOM_ID: task-2-subtraction-operator
:END:
Implement the subtraction operator
#+begin_src shell
DualNumber operator-(const DualNumber& dn1, const DualNumber& dn2)
#+end_src
in file =DualNumber.cpp=.
*** Task 3: Multiplication operator
:PROPERTIES:
:CUSTOM_ID: task-3-multiplication-operator
:END:
Implement the multiplication operator
#+begin_src shell
DualNumber operator*(const DualNumber& dn1, const DualNumber& dn2)
#+end_src
in file =DualNumber.cpp=.
* Solution
:PROPERTIES:
:CUSTOM_ID: solution
:END:
#+begin_src cpp
#include "DualNumber.h"
DualNumber operator+(const DualNumber &dn1, const DualNumber &dn2) {
DualNumber res;
double a = dn1.a + dn2.a;
double b = dn1.b + dn2.b;
res.a = a;
res.b = b;
return res;
}
DualNumber operator-(const DualNumber &dn1, const DualNumber &dn2) {
DualNumber res;
double a = dn1.a - dn2.a;
double b = dn1.b - dn2.b;
res.a = a;
res.b = b;
return res;
}
DualNumber operator*(const DualNumber &dn1, const DualNumber &dn2) {
DualNumber res;
double a = dn1.a * dn2.a;
double b = (dn1.a * dn2.b) + (dn1.b * dn2.a);
res.a = a;
res.b = b;
return res;
}
#+end_src
--------------
Made by JirR02 in Switzerland 🇨🇭