diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 81b8165..e2032eb 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -47,6 +47,7 @@ When writing or coding, try to stick to these guidelines: - Aim for simplicity and clarity—your work should be easy for others to follow. - Please use proper grammar and spelling. Everyone makes mistakes, but let’s keep them to a minimum. - Name your files and folders in English and using `kebab-case` (e.g., `linear-algebra`). +- Use `snake_case` for variable and function name or follow common naming convention - Be as descriptive as possible with your filenames and folder names (keep it short 👀). - Mixing languages in the same document is fine, but do it sparingly. - Get creative! You can leave a credit for yourself at the top of the document you created. ✨ diff --git a/README.md b/README.md index 3f5b2e3..1df4ebf 100644 --- a/README.md +++ b/README.md @@ -6,13 +6,13 @@

+[Bahasa Indonesia](README_ID.md) + > [!WARNING] -> This project is still under development. > This project is still in the early stages of development. We are working hard to make it better for everyone. If you have any suggestions or want to contribute, feel free to reach out to us. > [!NOTE] -> 🌐 Heads up! -> Currently, this project is available only in 🇮🇩 Indonesian language. We’re work on translations, so stay tuned! But if you're comfy with Indonesian, you're in the right place. 🚀 +> Currently, this project is available focused in 🇮🇩 Indonesian language. Translation for English is underway, if you would like to contribute to the translation effort or stay updated on the English version's progress, please feel free to open an issue or join our community discussion. ## Table of Contents diff --git a/README_ID.md b/README_ID.md new file mode 100644 index 0000000..e9c3590 --- /dev/null +++ b/README_ID.md @@ -0,0 +1,52 @@ +
+ Logo Math W Code +

Math W Code

+

+ Pelajari matematika dan implementasinya dalam pemrograman komputer. Pelajari semuanya mulai dari aritmatika hingga kalkulus dengan kode yang ditulis oleh berbagai kontributor dari seluruh dunia. +

+
+ +[English](README.md) + +> [!WARNING] +> Proyek ini masih dalam tahap awal pengembangan. Kami sedang bekerja keras untuk membuatnya lebih baik bagi semua orang. Jika Anda memiliki saran atau ingin berkontribusi, jangan ragu untuk menghubungi kami. + +> [!NOTE] +> Saat ini, proyek ini tersedia dalam bahasa 🇮🇩 Indonesia. Terjemahan untuk bahasa Inggris sedang dalam proses, jika Anda ingin berkontribusi dalam upaya penerjemahan atau ingin mendapatkan informasi terbaru tentang perkembangan versi bahasa Inggris, silakan buat issue atau bergabung dalam diskusi komunitas kami. + +## Daftar Isi +- [Daftar Isi](#daftar-isi) +- [Pendahuluan](#pendahuluan) +- [Instalasi](#instalasi) +- [Penggunaan](#penggunaan) +- [Berkontribusi](#berkontribusi) +- [Lisensi](#lisensi) +- [Kontak](#kontak) +- [Terima Kasih kepada Kontributor Kami](#terima-kasih-kepada-kontributor-kami) + +## 🌟 Pendahuluan +Math W Code adalah proyek yang digerakkan oleh komunitas yang bertujuan untuk membantu orang belajar matematika dan implementasinya dalam pemrograman komputer. Kami ingin semua orang belajar matematika dengan cara yang berbeda, dengan menggunakan kode untuk membantu memvisualisasikan dan memahami konsep dengan lebih baik. + +## 🧑‍💻 Instalasi +Siap untuk memulai? Berikut cara menyiapkan secara lokal dalam tiga langkah mudah: + +| Langkah | Perintah | +|---------|----------| +| Klon repositori | ```sh git clone https://github.com/xirf/mathwithcode.git``` | +| Masuk ke direktori proyek | ```sh cd mathwithcode``` | +| Instal dependensi | ```sh npm install``` | +| Jalankan! | ```npm run dev``` | + +Kemudian, buka browser Anda dan kunjungi ```http://localhost:5173``` untuk melihat situs dalam aksi. 🎉 + +## 🏗️ Berkontribusi +Kami 💖 kontributor! Ingin bergabung dalam keseruan? Luar biasa! Cukup lihat sekilas [Panduan Kontribusi](CONTRIBUTING.md) dan [Kode Etik](CODE_OF_CONDUCT.md) kami untuk memastikan kita semua berada di halaman yang sama. Baik itu memperbaiki bug, menyarankan fitur baru, atau menambahkan sentuhan kreatif, bantuan Anda selalu dihargai! + +## 🔐 Lisensi +Proyek ini dilisensikan di bawah Lisensi MIT. Lihat file LICENSE untuk detail lebih lanjut. + +## ✉️ Kontak +Punya pertanyaan, saran, atau hanya ingin menyapa? Kami senang mendengar dari Anda! Kirim email kepada kami di [itsandka@gmail.com](mailto:itsandka@gmail.com) + +## Terima Kasih kepada Kontributor Kami +Terima kasih BESAR kepada semua kontributor luar biasa yang telah membantu menjadikan proyek ini seperti sekarang. Lihat tim lengkapnya [di sini](https://github.com/xirf/mathwithcode/graphs/contributors). Kalian keren! 💪 diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts index 64627ae..f768939 100644 --- a/docs/.vitepress/config.ts +++ b/docs/.vitepress/config.ts @@ -1,40 +1,13 @@ -import { defineConfig } from 'vitepress' -import { sharedConfig } from './shared.config' -import sidebar from './sidebar' - +import { defineConfig } from "vitepress"; +import { sharedConfig } from "./shared.config"; +import { id } from "./id"; +import { en } from "./en"; // https://vitepress.dev/reference/site-config export default defineConfig({ ...sharedConfig, - locales: { - root: { - label: 'Indonesia', - lang: 'id-ID', - description: 'Belajar matematika dengan barisan kode', - themeConfig: { - nav: [ - { - text: 'Belajar', link: '/guide/', - }, - { - text: 'Donasi', link: 'https://trakteer.id/xirf' - } - ], - sidebar, - outline: { - level: [2,3], - label: 'Di halaman ini' - }, - editLink: { - pattern: 'https://github.com/xirf/mathwithcode/edit/master/docs/:path', - text: 'Perbaiki halaman ini di GitHub' - }, - footer: { - message: 'Dirilis di bawah lisensi MIT', - copyright: 'Copyright © 2024-present Andika & Contributors' - } - } - }, - } -}) + root: { label: 'Indonesia', ...id }, + en: { label: "English", ...en } + }, +}); diff --git a/docs/.vitepress/contributors.ts b/docs/.vitepress/contributors.ts index b608fd5..8877671 100644 --- a/docs/.vitepress/contributors.ts +++ b/docs/.vitepress/contributors.ts @@ -42,6 +42,12 @@ const plainContributors: Contributors[] = [ title: 'Project Lead', desc: 'Technology is my passion and dreaming about a better world with it and making it happen is a dream come true', }, + { + avatar: 'https://github.com/smintfy.png', + name: 'Smintfy', + github: 'smintfy', + twitter: 'smintfy', + }, { avatar: 'https://github.com/mininxd.png', name: 'Minin', @@ -66,8 +72,28 @@ const plainContributors: Contributors[] = [ avatar: 'https://github.com/up2dul.png', name: 'Abdul Malik', github: 'up2dul', - } + }, + { + + avatar: 'https://github.com/windofbay.png', + name: 'MasBay', + github: 'windofbay', + }, + { + avatar: "https://github.com/zevtyardt.png", + name: "Val", + github: "zevtyardt", + facebook: "mzyui", + sponsor: 'https://trakteer.id/mzyu', + }, + { + avatar: "https://github.com/fadjarrafi.png", + name: "Fadjar", + github: "fadjarrafi", + facebook: "rafifadjar21", + }, + ] const contributors = plainContributors.map(c => createLinks(c)) -export default contributors +export default contributors diff --git a/docs/.vitepress/en.ts b/docs/.vitepress/en.ts new file mode 100644 index 0000000..6b4d66a --- /dev/null +++ b/docs/.vitepress/en.ts @@ -0,0 +1,98 @@ +import { defineConfig } from "vitepress"; + +export const en = defineConfig({ + lang: "en-US", + description: "Learn math with lines of code", + themeConfig: { + nav: [ + { + text: "Learn", + link: "/en/guide/", + }, + { + text: "Donation", + link: "https://trakteer.id/xirf", + }, + ], + sidebar: sidebar(), + outline: { + level: [2, 3], + label: "On this page", + }, + editLink: { + pattern: + "https://github.com/xirf/mathwithcode/edit/master/docs/:path", + text: "Fix this page on GitHub", + }, + footer: { + message: "Released under the MIT license", + copyright: "Copyright © 2024-present Andika & Contributors", + }, + }, +}) + +function sidebar() { + return [ + { text: "Guide", link: "/en/guide/" }, + { + text: "Arithmetic", + collapsed: false, + items: [ + { text: "Numbers", link: "/en/arithmetic/numbers" }, + { + text: "Number Operations", + link: "/en/arithmetic/operation-on-number", + }, + { text: "Factors and Multiples", link: "/en/arithmetic/factors" }, + { text: "Percent", link: "/en/arithmetic/percent" }, + ], + }, + { + text: "Algebra", + collapsed: false, + items: [ + { text: "Function", link: "/en/algebra/function" }, + { text: "Linear Equation", link: "/en/algebra/linear-equation" }, + { text: "Quadratic Equation", link: "/en/algebra/quadratic-equation" }, + ], + }, + { + text: "Linear Algebra", + collapsed: false, + items: [ + { + text: "Linear Transformation", + link: "/en/linear-algebra/linear-transformation", + }, + { + text: "Matrix Multiplication", + link: "/en/linear-algebra/matrix-multiplication", + }, + ], + }, + { + text: "Statistics", + collapsed: false, + items: [ + { + text: "Measures of Location", + link: "/en/statistics/measures-concentration-dispersion", + }, + { + text: "Simple Linear Regression", + link: "/en/statistics/simple-linear-regression", + }, + ], + }, + { + text: "Calculus", + collapsed: false, + items: [ + { + text: "Limit", + link: "/en/calculus/limit", + }, + ], + }, + ] +} diff --git a/docs/.vitepress/id.ts b/docs/.vitepress/id.ts new file mode 100644 index 0000000..884a330 --- /dev/null +++ b/docs/.vitepress/id.ts @@ -0,0 +1,87 @@ +import { defineConfig } from "vitepress"; + +export const id = defineConfig({ + lang: 'id-ID', + description: 'Belajar matematika dengan barisan kode', + themeConfig: { + nav: [ + { + text: 'Belajar', link: '/guide/', + }, + { + text: 'Donasi', link: 'https://trakteer.id/xirf' + } + ], + sidebar: sidebar(), + outline: { + level: [2,3], + label: 'Di halaman ini' + }, + editLink: { + pattern: 'https://github.com/xirf/mathwithcode/edit/master/docs/:path', + text: 'Perbaiki halaman ini di GitHub' + }, + footer: { + message: 'Dirilis di bawah lisensi MIT', + copyright: 'Copyright © 2024-present Andika & Contributors' + } + }, +}) + +function sidebar() { + return [ + { text: "Panduan", link: "/guide/" }, + { + text: "Aritmatika", + collapsed: false, + items: [ + { text: "Bilangan", link: "/arithmetic/numbers" }, + { text: "Operasi Bilangan", link: "/arithmetic/operation-on-number", }, + { text: "Faktor dan Kelipatan", link: "/arithmetic/factors" }, + { text: "Persen", link: "/arithmetic/percent" }, + ], + }, + { + text: 'Aljabar', + collapsed: false, + items: [ + { text: 'Fungsi', link: '/algebra/function' }, + { text: 'Persamaan Linear', link: '/algebra/linear-equation' }, + { text: 'Persamaan Kuadrat', link: '/algebra/quadratic-equation'}, + ] + }, + { + text: 'Aljabar Linear', + collapsed: false, + items: [ + { text: 'Transformasi Linear', link: '/linear-algebra/linear-transformation' }, + { text: 'Matriks', link: '/linear-algebra/matrix' }, + { text: 'Vektor', link: '/linear-algebra/vector' }, + ] + }, + { + text: "Statistika", + collapsed: false, + items: [ + { + text: "Ukuran Letak", + link: "/statistics/measures-concentration-dispersion", + }, + { + text: "Regresi Linier Sederhana", + link: "/statistics/simple-linear-regression", + }, + ], + }, + { + text: "Kalkulus", + collapsed: false, + items: [ + { + text: "Limit", + link: "/calculus/limit", + }, + ], + }, + ] +} diff --git a/docs/.vitepress/shared.config.ts b/docs/.vitepress/shared.config.ts index 708c34c..ddc31cf 100644 --- a/docs/.vitepress/shared.config.ts +++ b/docs/.vitepress/shared.config.ts @@ -17,6 +17,9 @@ const headers = process.env.NODE_ENV === "production" ? [ ...baseHeader, umamiSc export const sharedConfig = defineConfig({ title: "Math W Code", description: "Belajar matematika dengan barisan kode", + rewrites: { + 'id/:rest*': ':rest*' + }, cleanUrls: true, head: headers, metaChunk: true, diff --git a/docs/.vitepress/sidebar.ts b/docs/.vitepress/sidebar.ts deleted file mode 100644 index b566e88..0000000 --- a/docs/.vitepress/sidebar.ts +++ /dev/null @@ -1,38 +0,0 @@ -export default [ - { text: 'Panduan', link: '/guide/' }, - { - text: 'Aritmatika', - collapsed: false, - items: [ - { text: 'Bilangan', link: '/arithmetic/numbers' }, - { text: 'Operasi Bilangan', link: '/arithmetic/operation-on-number' }, - { text: 'Faktor dan Kelipatan', link: '/arithmetic/factors' }, - { text: 'Persen', link: '/arithmetic/percent' }, - ] - }, - { - text: 'Aljabar', - collapsed: false, - items: [ - { text: 'Fungsi', link: '/algebra/function' }, - { text: 'Persamaan Linear', link: '/algebra/linear-equation' }, - { text: 'Persamaan Kuadrat', link: '/algebra/quadratic-equation' }, - ] - }, - { - text: 'Aljabar Linear', - collapsed: false, - items: [ - { text: 'Transformasi Linear', link: '/linear-algebra/linear-transformation' }, - { text: 'Matriks', link: '/linear-algebra/matrix' }, - { text: 'Vektor', link: '/linear-algebra/vector' }, - ] - }, - { - text: 'Statistika', - collapsed: false, - items: [ - { text: 'Ukuran Letak', link: '/statistics/measures-concentration-dispersion' }, - ] - } -] \ No newline at end of file diff --git a/docs/.vitepress/theme/components/Consent.vue b/docs/.vitepress/theme/components/Consent.vue index bdc0931..9ef36ee 100644 --- a/docs/.vitepress/theme/components/Consent.vue +++ b/docs/.vitepress/theme/components/Consent.vue @@ -1,6 +1,6 @@ \ No newline at end of file + diff --git a/docs/.vitepress/theme/components/HomePage.vue b/docs/.vitepress/theme/components/HomePage.vue index 790354e..eedf1da 100644 --- a/docs/.vitepress/theme/components/HomePage.vue +++ b/docs/.vitepress/theme/components/HomePage.vue @@ -1,14 +1,29 @@ \ No newline at end of file + diff --git a/docs/arithmetic/percent.md b/docs/arithmetic/percent.md deleted file mode 100644 index 156eb53..0000000 --- a/docs/arithmetic/percent.md +++ /dev/null @@ -1,113 +0,0 @@ -# Persen - -Pernah dapat diskon pas belanja?, biasanya kalo gak di coret ya pake tanda persen ($%$). Nah, persen ini adalah cara kita mengukur seberapa besar atau kecil suatu nilai dibandingkan dengan nilai aslinya. - -Misalnya kamu beli baju seharga Rp. $100.000$ tapi kamu dapat diskon $20\%$, berarti kamu bisa beli bajunya dengan harga Rp. $80.000$. - -Cara ngitung persen itu gampang banget, kita bisa pakai rumus: -$$ persen = \frac{nilai}{100} \times persen $$ - -Jadi kalo kita mau ngitung $20\%$ dari $100.000$ kita bisa tulis: -$$ persen = \frac{100.000}{100} \times 20\% = 20.000 $$ - -karena dibagi $100$ jadi kita bisa kurangi dua nol dari $100.000$ jadi $1.000$ dan dikalikan $20$ jadi $20.000$. - -Kalo diubah ke kodingan, kita bisa tulis seperti ini: -:::tabs -== Javascript -```js -let harga = 100000; -let diskon = 20; -let persen = (harga / 100) * diskon; // 20000 -``` -== Kotlin -```kt -val harga = 100000 -val diskon = 20 -val persen = (harga / 100) * diskon // 20000 -``` -== C++ -```cpp -int harga = 100000; -int diskon = 20; -int persen = (harga / 100) * diskon; // 20000 -``` -== Python -```python -harga = 100000 -diskon = 20 -persen = (harga / 100) * diskon # 20000.0 -``` -::: - -## Mencari Nilai Asli - -Kalo sebelumnya kita ngitung persen dari nilai asli, sekarang kita akan mencari nilai asli dari nilai persen tersebut. Caranya tinggal dibalik aja rumusnya jadi: -$$ nilai = \frac{persen}{persen} \times 100 $$ - -Misalnya kita punya nilai persen sebesar $20.000$ dan kita mau cari nilai aslinya, kita bisa tulis: -$$ nilai = \frac{20.000}{20\%} \times 100 = 100.000 $$ - -Kalo diubah ke kodingan, kita bisa tulis seperti ini: -:::tabs -== Javascript -```js -let persen = 20000; -let diskon = 20; -let harga = (persen / diskon) * 100; // 100000 -``` -== Kotlin -```kt -val persen = 20000 -val diskon = 20 -val harga = (persen / diskon) * 100 // 100000 -``` -== C++ -```cpp -int persen = 20000; -int diskon = 20; -int harga = (persen / diskon) * 100; // 100000 -``` -== Python -```python -persen = 20000 -diskon = 20 -persen = (persen / diskon) * 100 # 100000.0 - -``` -::: - -## Mencari Persen - -Kalo sebelumnya kita ngitung persen dari nilai asli, sekarang kita akan mencari nilai persen dari nilai asli tersebut. Rumusnya kita ubah jadi: -$$ persen = \frac{nilai}{nilai} \times 100 $$ -Misalnya kita punya nilai asli sebesar $100.000$ dan kita mau cari persennya, kita bisa tulis: -$$ persen = \frac{100.000}{100.000} \times 100 = 20\% $$ - -Kalo diubah ke kodingan, kita bisa tulis seperti ini: -:::tabs -== Javascript -```js -let harga = 100000; -let diskon = 20000; -let persen = (diskon / harga) * 100; // 20 -``` -== Kotlin -```kt -val harga = 100000 -val diskon = 20000 -val persen = (diskon / harga) * 100 // 20 -``` -== C++ -```cpp -int harga = 100000; -int diskon = 20000; -int persen = (diskon / harga) * 100; // 20 -``` -== Python -```python -harga = 100000 -diskon = 20000 -persen = (diskon / harga) * 100 # 20.0 -``` -::: \ No newline at end of file diff --git a/docs/en/algebra/function.md b/docs/en/algebra/function.md new file mode 100644 index 0000000..5808e8f --- /dev/null +++ b/docs/en/algebra/function.md @@ -0,0 +1,387 @@ +--- +contributors: + - name: "Anka Tama" + username: "xirf" +--- +# Function + +In mathematics, an algebraic function is a notation that connects two sets of numbers. +This function is usually written in the form $f(x) = y$ +Where $f$ is a function, $x$ is the input, and $y$ is the output. + +Algebraic functions have a similar concept to functions in programming where both have *input* dan *output*. +For example, the function $f(x) = 2x + 3$ when we make it as a function in programming, it will be as follows: + +:::tabs key:lang +== Javascript +``` js +function myFunction(x) { + return 2 * x + 3; +} +``` +== C++ +``` cpp +int myFunction(int x) { + return 2 * x + 3; +} +``` +== Kotlin +``` kotlin +fun myFunction(x: Int): Int { + return 2 * x + 3 +} +``` +== Python +``` python +def myFunction(x): + return 2 * x + 3 +``` +::: + +## Domain, Codomain, and Range +**Domain** is the collection of all input values ​​allowed in the function. +In mathematics, the domain is the collection of all values ​​of x that satisfy a function. + +**Codomain** itself is the set of all possible output values ​​of a function. +While **range** is the collection of all output values ​​that are actually produced by the function. + +In programming, **domain** and **codomain** can be interpreted as the input and output data types of a defined function. + +In other words, domain in the context of programming is the type of data that a function can accept as input (*parameter*), +and codomain is the type of data that the function produces as output. + +## Types of Functions +There are several types of functions that are often used in mathematics, including: + +### Fungsi Linear +A linear function is a function whose form is $f(x) = ax + b$ Where $a$ and $b$ is a constant. +This function has a graph in the form of a straight line. +For example, the function $f(x) = 1x + 0.5$ will produce a graph like the following: + + + +### Quadratic Function +A quadratic function is a function whose form is $f(x) = ax^2 + bx + c$ where $a$, $b$, and $c$ is a constant. +This function has a parabolic graph. + + + +### Exponential Function +Exponential function is a function whose form is $f(x) = a^x$ where $a$ is a constant. +This function has a graph in the form of an increasing curve. + + + +### Logarithmic Function +The logarithmic function is a function that is the opposite of the exponential function. +This function has the form $f(x) = \log_a(x)$ where $a$ is a constant. This function has a graph in the form of a decreasing curve. + + + +### Trigonometric Functions +Trigonometric functions are functions that involve trigonometric functions such as sin, cos, tan, and so on. +This function has a wave-shaped graph. Below is an example of a trigonometric function graph where +- Red is the function $sin(x)$ +- Green is the function $cos(x)$ +- Purple is the function $tan(x)$ + + +## Operations on Functions + +### Addition and Subtraction Functions +Addition and subtraction of functions is done by adding or subtracting one function to another. For example +$$f(x) = 2x + 3$$ +$$g(x) = 3x - 2$$ + +So the sum of the two functions is + +$$\begin{align*} + (f + g)(x) &= f(x) + g(x) \\ + &= (2x + 3) + (3x - 2) \\ + &= 5x + 1 +\end{align*}$$ + +If we make it as a function in programming, it will be like the followings: +:::tabs key:lang +== Javascript +``` js +function f(x) { + return 2 * x + 3; +} +function g(x) { + return 3 * x - 2; +} +function fg(x) { + return f(x) + g(x); +} +``` +== C++ +``` cpp +int f(int x) { + return 2 * x + 3; +} +int g(int x) { + return 3 * x - 2; +} +int fg(int x) { + return f(x) + g(x); +} +``` +== Kotlin +``` kotlin +fun f(x: Int): Int { + return 2 * x + 3; +} +fun g(x: Int): Int { + return 3 * x - 2; +} +fun fg(x: Int): Int { + return f(x) + g(x); +} +``` +== Python +``` python +def f(x): + return 2 * x + 3 + +def g(x): + return 3 * x - 2 + +def fg(x): + return f(x) + g(x) + +``` +::: + +### Multiplication of Functions +Function multiplication is done by multiplying one function by another function. For example +$$f(x) = 2x + 3$$ +$$g(x) = 3x - 2$$ + +So the multiplication of the two functions is + +$$\begin{align*} + (f \cdot g)(x) &= f(x) \cdot g(x) \\ + &= (2x + 3) \cdot (3x - 2) \\ + &= 6x^2 + 4x - 6 +\end{align*}$$ + +If we make it as a function in programming, it will be like the followings: + +:::tabs key:lang +== Javascript +``` js +function f(x) { + return 2 * x + 3; +} +function g(x) { + return 3 * x - 2; +} +function fg(x) { + return f(x) * g(x); +} +``` +== C++ +``` cpp +int f(int x) { + return 2 * x + 3; +} +int g(int x) { + return 3 * x - 2; +} +int fg(int x) { + return f(x) * g(x); +} +``` +== Kotlin +``` kotlin +fun f(x: Int): Int { + return 2 * x + 3; +} +fun g(x: Int): Int { + return 3 * x - 2; +} +fun fg(x: Int): Int { + return f(x) * g(x); +} +``` +== Python +``` python +def f(x): + return 2 * x + 3 + +def g(x): + return 3 * x - 2 + +def fg(x): + return f(x) * g(x) +``` +::: + +### Function Composition +A composition of function is a function whose result is another function. For example + +$$f(x) = 2x + 3$$ +$$g(x) = 3x - 2$$ + +So the composition function of the two functions is + +$$\begin{align*} + (f \circ g)(x) &= f(g(x)) \\ + &= f(3x - 2) \\ + &= 2(3x - 2) + 3 \\ + &= 6x - 4 + 3 \\ + &= 6x - 1 +\end{align*}$$ + +If we make it as a function in programming, it will be like the followings: +:::tabs key:lang +== Javascript +``` js +function f(x) { + return 2 * x + 3; +} +function g(x) { + return 3 * x - 2; +} +function fog(x) { + return f(g(x)); +} +``` +== C++ +``` cpp +int f(int x) { + return 2 * x + 3; +} +int g(int x) { + return 3 * x - 2; +} +int fog(int x) { + return f(g(x)); +} +``` +== Kotlin +``` kotlin +fun f(x: Int): Int { + return 2 * x + 3; +} +fun g(x: Int): Int { + return 3 * x - 2; +} +fun fog(x: Int): Int { + return f(g(x)); +} +``` +== Python +``` python +def f(x): + return 2 * x + 3 + +def g(x): + return 3 * x - 2 + +def fog(x): + return f(g(x)) +``` +::: + +> [!NOTE] Properties of composition functions +> - The composition function is not commutative, meaning that $f \circ g \neq g \circ f$ +> - Associative composition function, meaning $(f \circ g) \circ h = f \circ (g \circ h)$ +> - The composition function has an identity element, meaning that $f \circ I = f$ where $I$ is an identity function + +### Inverse Function + +An inverse function is a function whose result is another function that is the inverse of that function. For example + +$$f(x) = 2x + 3$$ + +So to find the inverse of the function, we have to find $f^{-1}(x)$ dimana $f^{-1}(f(x)) = x$. + +The steps to find the inverse of a function are as follows: + +1. Change the form of $y = f(x)$ to $x = f^{-1}(y)$ +2. Solve $x$ from the equation +3. Subtitute $x$ with $f^{-1}(y)$ +4. Solve the equation + +Example of finding the inverse of a function $f(x) = 2x + 6$ are as follows: + +$$\begin{align*} + y &= f(x) = 2x + 6 \\ + 2x &= y - 6 \\ + x &= \frac{1}{2}y-3 +\end{align*}$$ + +Then the inverse of the function $f(x) = 2x + 6$ is $f^{-1}(x) = \frac{1}{2}x-3$ + +When we make it as a function in programming where the value $x$ is known and the output is the value $y$, then it will be as follows: +:::tabs key:lang +== Javascript +``` js +function inverseFunction(y, a, b) { + if (a === 0) { + throw new Error("Value of a cannot be 0"); + } + return (y - b) / a; +} + +const a = 2; // Suppose a = 2 +const b = 3; // Suppose b = 3 +const y = 7; // Value of y = (f(x)) +// f(x) = 2x + 3 +const x = inverseFunction(y, a, b); +console.log(`Inverse of f(${y}) is x = ${x}`); +``` +== C++ +``` cpp +int inverseFunction(int y, int a, int b) { + if (a == 0) { + throw "Value of a cannot be 0"; + } + return (y - b) / a; +} + +int main() { + int a = 2; // Suppose a = 2 + int b = 3; // Suppose b = 3 + int y = 7; // Value of y = (f(x)) + // f(x) = 2x + 3 + int x = inverseFunction(y, a, b); + cout << "Inverse of f(" << y << ") is x = " << x << endl; + return 0; +} +``` +== Kotlin +``` kotlin +fun inverseFunction(y: Int, a: Int, b: Int): Int { + if (a == 0) { + throw IllegalArgumentException("Value of a cannot be 0") + } + return (y - b) / a +} + +fun main() { + val a = 2 // Suppose a = 2 + val b = 3 // Suppose b = 3 + val y = 7 // Value of y = (f(x)) + // f(x) = 2x + 3 + val x = inverseFunction(y, a, b) + println("Inverse of f($y) is x = $x") +} +``` +== Python +``` python +def inverseFunction(y, a, b): + if a == 0: + raise Exception("Value of a cannot be 0") + return (y - b) / a + +a = 2 # Suppose a = 2 +b = 3 # Suppose b = 3 +y = 7 # Value of y = (f(x)) +# f(x) = 2x + 3 +x = inverseFunction(y, a, b) +print(f"Inverse of f({y}) is x = {x}") +``` +::: diff --git a/docs/linear-algebra/vector-space.md b/docs/en/algebra/graph.md similarity index 100% rename from docs/linear-algebra/vector-space.md rename to docs/en/algebra/graph.md diff --git a/docs/en/algebra/linear-equation.md b/docs/en/algebra/linear-equation.md new file mode 100644 index 0000000..56ed255 --- /dev/null +++ b/docs/en/algebra/linear-equation.md @@ -0,0 +1,334 @@ +# Linear Equations + +Linear equations can be interpreted as an equation whose terms have constants (fixed values) with a single variable. +This equation is called linear because the relationship between its variables forms a straight line when depicted in a two-dimensional graph. +Before starting, we must understand several things below + +1. **Variable**: A substitute for a number whose value is not yet known. +2. **Coefficient**: A number that multiplies a variable. +3. **Constant**: A number that has no variables. +4. **Term**: Part of an equation consisting of variables, coefficients, and constants. + +Linear equations also have several rules/properties that must be understood, including: + +- Addition and subtraction of numbers on both sides will not change the value of the equation. +- Multiplication and division of numbers on both sides does not change the value of the equation. +- The value of the equation does not change if the same number is added or subtracted from both sides. +- If you move sides of an equation, then addition changes to subtraction, multiplication changes to division, and vice versa. + +## Linear Equation in One Variable + +A linear equation of one variable is an equation that has one variable. +This equation is usually written in the form $ax + b = c$ where $a$, $b$, and $c$ is a real number and $x$ is a variable. + +Example of a linear equation in one variable: +$$ 2x + 3 = 7 $$ + +To find out the value of $x$ that satisfies the equation, we have to find the value of $x$ which makes both sides of the equation equal. Here are the steps: + +1. Eliminate the constant on the left side by reducing the constant on the left side with the constant on the right side. + +$$\begin{align*} + 2x + 3 - 3 &= 7 - 3 \\ + 2x &= 4 +\end{align*}$$ + +2. Eliminate the coefficient of the variable by dividing both sides by the coefficient of the variable. + +$$\begin{align*} + \frac{2x}{2} &= \frac{4}{2} \\ + x &= 2\\ +\end{align*}$$ + +3. Therefore the value of $x$ which satisfies the equation is $x = 2$. + +If we implemented it in code, the code would be like this: +:::tabs key:lang +==javascript + +```js +function linearEquation(a, b, c) { + // Equation: a * x + b = c + const x = (c - b) / a; + return x; +} +console.log(linearEquation(2, 3, 7)); // Output: 2 +``` + +==kotlin + +```kotlin +val a = 2 +val b = 3 +val c = 7 + +// Equation: a * x + b = c +val x = (c - b) / a +println("Value of x is: $x") +``` + +== C++ + +```cpp +int linearEquation(int a, int b, int c) { + // Equation: a * x + b = c + int x = (c - b) / a; + return x; +} + +int main() { + int a = 2; + int b = 3; + int c = 7; + int x = linearEquation(a, b, c); + cout << "Value of x is: " << x << endl; + return 0; +} +``` + +==Python +```python +def linearEquation(a, b, c): + # Equation: a * x + b = c + x = (c - b) / a + return x + +a, b, c, = 2, 3, 7 +x = linearEquation(a, b, c) +print(f"Value of x is: {x}") +``` + +::: + +## Linear Equations in Two Variables + +As the name suggests, this equation has two variables which are usually written in the form $ax + by = c$ where $a$, $b$, and $c$ is a real number, where $x$ and $y$ iss a variable. + +Example of a linear equation of two variables: +$$ 2x + 3y = 7 $$ + +There are 2 ways to solve this kind of equations, namely by using the substitution and elimination methods. +For the substitution method, we can replace one of the variables with a known value. +While for the elimination method, we can eliminate one of the variables by multiplying one of the equations by a certain number. + +### Substitution Method + +The following is an example of solving the equation above using the substitution method: + +1. First we choose one of the variables to isolate, for example we choose $x$. +2. The variables that we isolate then we save and move the others to the right. + $$ 2x = 7 - 3y $$ +3. Because the isolated value is $2x$ we then divide both sides by $2$. + +$$\begin{align*} +x &= \frac{7 - 3y}{2} \\ +x &= \frac{7}{2} - \frac{3y}{2} \\ +\end{align*}$$ + +4. So we get a parametric solution from $x$ + +This parametric value is what will be the value later $y$ yang kita masukkan akan menghasilkan nilai $x$ yang sesuai. Misalnya nilai $y = 1$ maka: + + +$$\begin{align*} +x &= \frac{7 - 3(1)}{2} \\ +x &= \frac{4}{2} \\ +x &= 2 +\end{align*}$$ + +What if we implement this problem as code? Here is an example of its implementation: +:::tabs key:lang +==javascript + +```js +function pldv(a, b, c, y) { + let x = (c - b * y) / a; + return { x, y }; +} + +// 2x + 3y = 7 where y = 1 +console.log(pldv(2, 3, 7, 1)); // Output: { x: 2, y: 1 } +``` + +==kotlin + +```kotlin +fun pldv(a: Int, b: Int, c: Int, y: Int): Pair { + val x = (c - b * y) / a + return Pair(x, y) +} + +// 2x + 3y = 7 where y = 1 +println(pldv(2, 3, 7, 1)) // Output: (2, 1) +``` + +== C++ + +```cpp +#include +#include + +std::pair pldv(int a, int b, int c, int y) { + int x = (c - b * y) / a; + return std::make_pair(x, y); +} + +int main() { + // 2x + 3y = 7 where y = 1 + auto result = pldv(2, 3, 7, 1); + std::cout << "Output: (" << result.first << ", " << result.second << ")" << std::endl; + return 0; +} +``` +== Python +``` python +def pldv(a, b, c, y): + x = (c - b * y) / a + return x, y + +# 2x + 3y = 7 where y = 1 +print(pldv(2, 3, 7, 1))# Output: (x: 2.0, y: 1) +``` +::: + +### Elimination Method + +If we use the elimination method, we need 2 equations for comparison. For example, we have the following 2 equations: +$$ 2x + 3y = 7 $$ +$$ 3x - 2y = 8 $$ +If we already have two equations, we can eliminate one of the variables by multiplying one of the equations by a certain number. Here are the steps: + +1. Convert both equations to standard form. + $$ 2x + 3y = 7$$ + $$ 3x - 2y = 8$$ +2. We will eliminate the variables $y$ y multiplying equation (1) by $2$ and equation (2) with $3$ (we choose the same coefficients). + $$ 4x + (3 \times 2y) = 7 \times 2$$ + $$ 9x - (2 \times 3y) = 8 \times 3$$ +
+ + $$ 4x + 6y = 14$$ + $$ 9x - 6y = 24$$ +3. Well, the value of $y$ is the same, so now all we have to do is reduce equation (1) by equation (2). + $$ 4x + 6y = 14$$ + $$ 9x - 6y = 24$$ +
+ + $$ -5x = -10$$ + +4. We divide both sides by $-5$. + $$ \frac{-5x}{-5} = \frac{-10}{-5}$$ + $$ x = 2$$ + +5. Now that we have got the value $x$ now we look for the value $y$ by subtituting $x$ to one of the equations. + + $$ 2x + 3y = 7$$ + $$ 2(2) + 3y = 7$$ + $$ 4 + 3y = 7$$ + $$ 3y = 3$$ + $$ y = 1$$ + +6. So the value of $x$ and $y$ that satisfies the equation is $x = 2$ and $y = 1$. + +What if we implement this problem as code? Here is an example of its implementation: +:::tabs key:lang +==javascript + +```js +function eliminationMethod(a1, b1, c1, a2, b2, c2) { + // Calculate coefficient for elimination + let factor = a2 / a1; + + // Create a new equation by subtracting + let newB2 = b2 - factor * b1; + let newC2 = c2 - factor * c1; + + // Solve for y + let y = newC2 / newB2; + + // Calculate x by subtituting y to equation 1 + let x = (c1 - b1 * y) / a1; + + return { x: x, y: y }; +} + +// 2x - 3y = 7 and 3x - 2y = 8 +console.log(eliminationMethod(2, 3, 7, 3, -2, 8)); // Output: { x: 2, y: 1 } +``` +== kotlin + +```kotlin +fun eliminationMethod(a1: Int, b1: Int, c1: Int, a2: Int, b2: Int, c2: Int): Pair { + // Calculate coefficient for elimination + val factor = a2 / a1 + + // Create a new equation by subtracting + val newB2 = b2 - factor * b1 + val newC2 = c2 - factor * c1 + + // Solve for y + val y = newC2 / newB2 + + // Calculate x by subtituting y to equation 1 + val x = (c1 - b1 * y) / a1 + + return Pair(x, y) +} + +// 2x - 3y = 7 and 3x - 2y = 8 +println(eliminationMethod(2, 3, 7, 3, -2, 8)) // Output: (2, 1) +``` +== C++ + +```cpp +#include +#include + +pair eliminationMethod(double a1, double b1, double c1, double a2, double b2, double c2) { + // Calculate coefficient for elimination + double factor = a2 / a1; + + // Create a new equation by subtracting + double newB2 = b2 - factor * b1; + double newC2 = c2 - factor * c1; + + // Solve for y + double y = newC2 / newB2; + + // Calculate x by subtituting y to equation 1 + double x = (c1 - b1 * y) / a1; + + return make_pair(x, y); +} + +int main() { + auto result = eliminationMethod(2, 3, 7, 4, -5, 10); + cout << "x: " << result.first << ", y: " << result.second << endl; + // Output: x: 3, y: -1 + return 0; +} +``` + +==Python + +```python +def eliminationMethod(a1, b1, c1, a2, b2, c2): + # Calculate coefficient for elimination + factor = a2 / a1 + + # Create a new equation by subtracting + newB2 = b2 - factor * b1 + newC2 = c2 - factor * c1 + + # Solve for y + y = newC2 / newB2 + + # Calculate x by subtituting y to equation 1 + x = (c1 - b1 * y) / a1 + + return x, y + +# Example: 2x - 3y = 7 and 3x - 2y = 8 +x, y = eliminationMethod(2, 3, 7, 3, -2, 8) +print(f"x: {x}, y: {y}") # Output: x: 2, y: 1 +``` +::: diff --git a/docs/en/algebra/quadratic-equation.md b/docs/en/algebra/quadratic-equation.md new file mode 100644 index 0000000..af15bc4 --- /dev/null +++ b/docs/en/algebra/quadratic-equation.md @@ -0,0 +1,226 @@ +--- +contributors: + - name: "Anka Tama" + username: "xirf" +--- + +# Quadratic Equation + +A quadratic equation can be defined as a polynomial equation (an equation consisting of several terms) of degree two, +which implies that this equation consists of at least one term squared. The general form of a quadratic equation is: + +$$ax^2 + bx + c = 0$$ + +Where $x$ is an unknown variable and $a$, $b$, $c$ is a numerical coefficient. For example, $x^2 + 2x +1$ is a quadratic equation. +Here, $a ≠ 0$ because if it is equal to zero then the equation is no longer quadratic and will become a linear equation, such as $bx + c = 0$. + + +
+ +Quadratic equation graph of $f(x) = 0.1x^2 + 0.5 - 0.3x$ + +
+ +## General Formula + +The roots of a quadratic equation can be found using the quadratic formula. The quadratic formula is: + +$$x = \frac{-b ± \sqrt{b^2 - 4ac}}{2a}$$ + +Where $±$ here means two possible values ​​for $x$. +This formula is known as the quadratic formula or abc formula. +This formula can be used to find the roots of a quadratic equation $ax^2 + bx + c = 0$. + +## Discriminant + +The discriminant is the part of the quadratic formula that is located under the root sign. +The discriminant is used to determine the type of roots of a quadratic equation. The discriminant is defined as: + +$$D = b^2 - 4ac$$ + +Where $a$, $b$, and $c$ is the coefficient of the quadratic equation $ax^2 + bx + c = 0$. +Here are some possible discriminant values: + +- If $D > 0$, then the quadratic equation has real number solutions. +- If $D = 0$, then the quadratic equation has two equal real roots. +- If $D < 0$, then the quadratic equation has two complex roots. + +## Using the Quadratic Formula + +The roots of a quadratic equation are two values $x$, which is obtained by solving the quadratic equation. +The roots of this quadratic equation are also called the zeros of the equation. +For example, the roots of the equation $x^2 - 3x - 4 = 0$ can be searched using the following method: + +$$\begin{align*} +x &= \frac{-b \pm \sqrt{b^2 - 4ac}}{2a} \\ +x &= \frac{-(-3) \pm \sqrt{3^2 - 4\cdot1\cdot(-4)}}{2\cdot1} \\ +x &= \frac{3 \pm \sqrt{9 - - 16}}{2} \\ +x &= \frac{3 \pm \sqrt{9 + 16}}{2} \\ +x &= \frac{3 \pm \sqrt{25}}{2} \\ +x &= \frac{3 \pm 5}{2} +\end{align*}$$ + +Let's simplify it to +$$x = \frac{3 ± 5}{2}$$ +$$x = \frac{8}{2} \text{ atau } x = -\frac{2}{2}$$ + +Which eventually becomes $x = 4$ or $x = -1$. So, the roots of the equation $x^2 - 3x - 4 = 0$ is $x = 4$ and $x = -1$. + +If implemented in code, the result would be like this: + +:::tabs key:lang +==Javascript + +```js +function findRootsStepByStep(a, b, c) { + // Step 1: Calculate b^2 and 4ac + const bSquared = b * b; + const fourAC = 4 * a * c; + Step2: Calculate discriminant + const discriminant = bSquared - fourAC; + + if (discriminant >= 0) { + // If discriminant >= 0, then continue with real roots + // Step 3: Calculate the roots from discriminant + const sqrtDiscriminant = Math.sqrt(discriminant); + // Step 4: Calculate two possible values for x + const root1 = (-b + sqrtDiscriminant) / (2 * a); + const root2 = (-b - sqrtDiscriminant) / (2 * a); + console.log(`x1 = (-${b} + ${sqrtDiscriminant}) / (2 * ${a}) = ${root1}`); + console.log(`x2 = (-${b} - ${sqrtDiscriminant}) / (2 * ${a}) = ${root2}`); + console.log(`The roots are: x1 = ${root1} dan x2 = ${root2}`); + } else { + // If discriminant < 0, then it's a complex root + const realPart = -b / (2 * a); + const imaginaryPart = Math.sqrt(-discriminant) / (2 * a); + console.log(`x1 = ${realPart} + ${imaginaryPart}i`); + console.log(`x2 = ${realPart} - ${imaginaryPart}i`); + } +} + +// Example for equation x^2 - 3x - 4 = 0 +const a = 1; +const b = -3; +const c = -4; +findRootsStepByStep(a, b, c); +``` + +== C++ + +```cpp +#include +#include + +fun findRootsStepByStep(a: Double, b: Double, c: Double) { + // Step 1: Calculate b^2 and 4ac + val bSquared = b * b + val fourAC = 4 * a * c + + Step2: Calculate discriminant + val discriminant = bSquared - fourAC + + if (discriminant >= 0) { + // If discriminant >= 0, then continue with real roots + // Step 3: Calculate the roots from discriminant + val sqrtDiscriminant = sqrt(discriminant) + + // Step 4: Calculate two possible values for x + val root1 = (-b + sqrtDiscriminant) / (2 * a) + val root2 = (-b - sqrtDiscriminant) / (2 * a) + println("x1 = (-$b + $sqrtDiscriminant) / (2 * $a) = $root1") + println("x2 = (-$b - $sqrtDiscriminant) / (2 * $a) = $root2") + println("The roots are: x1 = $root1 dan x2 = $root2") + } else { + // If discriminant < 0, then it's a complex root + val realPart = -b / (2 * a) + val imaginaryPart = sqrt(-discriminant) / (2 * a) + println("x1 = $realPart + ${imaginaryPart}i") + println("x2 = $realPart - ${imaginaryPart}i") + } +} + +fun main() { + // Example for equation x^2 - 3x - 4 = 0 + val a = 1.0 + val b = -3.0 + val c = -4.0 + findRootsStepByStep(a, b, c) +} + +``` + +== Kotlin + +```kotlin +import kotlin.math.sqrt + +fun findRootsStepByStep(a: Double, b: Double, c: Double) { + // Step 1: Calculate b^2 and 4ac + val bSquared = b * b + val fourAC = 4 * a * c + + Step2: Calculate discriminant + val discriminant = bSquared - fourAC + + if (discriminant >= 0) { + // If discriminant >= 0, then continue with real roots + // Step 3: Calculate the roots from discriminant + val sqrtDiscriminant = sqrt(discriminant) + + // Step 4: Calculate two possible values for x + val root1 = (-b + sqrtDiscriminant) / (2 * a) + val root2 = (-b - sqrtDiscriminant) / (2 * a) + println("x1 = (-$b + $sqrtDiscriminant) / (2 * $a) = $root1") + println("x2 = (-$b - $sqrtDiscriminant) / (2 * $a) = $root2") + println("The roots are: x1 = $root1 dan x2 = $root2") + } else { + // If discriminant < 0, then it's a complex root + val realPart = -b / (2 * a) + val imaginaryPart = sqrt(-discriminant) / (2 * a) + println("x1 = $realPart + ${imaginaryPart}i") + println("x2 = $realPart - ${imaginaryPart}i") + } +} + +fun main() { + // Example for equation x^2 - 3x - 4 = 0 + val a = 1.0 + val b = -3.0 + val c = -4.0 + findRootsStepByStep(a, b, c) +} +``` +== Python +``` python +import math + +def findRootsStepByStep(a, b, c): + # Step 1: Calculate b^2 and 4ac + bSquared = b * b + fourAC = 4 * a * c + # Step 2: Calculate discriminant + discriminant = bSquared - fourAC + + if discriminant >= 0: + # If discriminant >= 0, then continue with real roots + # Step 3: Calculate the roots from discriminant + sqrtDiscriminant = math.sqrt(discriminant) + # Step 4: Calculate two possible values for x + root1 = (-b + sqrtDiscriminant) / (2 * a) + root2 = (-b - sqrtDiscriminant) / (2 * a) + print(f"x1 = (-{b} + {sqrtDiscriminant}) / (2 * {a}) = {root1}") + print(f"x2 = (-{b} - {sqrtDiscriminant}) / (2 * {a}) = {root2}") + print(f"The roots are: x1 = {root1} dan x2 = {root2}") + else: + # If discriminant < 0, then it's a complex root + realPart = -b / (2 * a) + imaginaryPart = math.sqrt(-discriminant) / (2 * a) + print(f"x1 = {realPart} + {imaginaryPart}i") + print(f"x2 = {realPart} - {imaginaryPart}i") + +# Example for equation x^2 - 3x - 4 = 0 +a = 1 +b = -3 +c = -4 +findRootsStepByStep(a, b, c) +``` diff --git a/docs/en/arithmetic/factors.md b/docs/en/arithmetic/factors.md new file mode 100644 index 0000000..4467e88 --- /dev/null +++ b/docs/en/arithmetic/factors.md @@ -0,0 +1,379 @@ +--- +title: Factor and Multiples +description: Factorization, prime factorization, factor trees, GCF, LCM +--- + +# Factorization + +Factorization is the process of breaking down a number into its factors. Factors here are numbers that can be multiplied to produce the number we want. + +For example, the factorization of 12 is 2 and 6, because $2 \times 6 = 12$. The factorization of 6 is 2 and 3, because $2 \times 3 = 6$. + +## Prime Factorization + +Prime factorization is a factorization in which all the resulting factors are prime numbers. A prime number is a number that can only be divided by 1 and itself. + +Examples: + +- The prime factor of 12 is $12=2×2×3$, because 12 can be divided into 2 times 6, then 6 can be divided again into 2 times 3. +- The prime factor of 30 is $30=2×3×5$, because 30 can be divided into 2, 3, and 5, all of which are prime numbers. + +## Factor Tree + +Put it simply, we can find factorization by using a factor tree where we perform repeated division until the number we divide is a prime number. + +For example, if we have the number 100, then the factor tree is like this: + + + 2 + + 2 + + 5 + + 0 + 0 + 1 + + 0 + 5 + + 5 + 2 + + 5 + + +From the factor tree above we can see that the factorization of 100 is $2 \times 2 \times 5 \times 5$ or $2^2 \times 5^2$. We can write the factorization of 100 as $2^2 \times 5^2$. + +In programming, we can use _loop_ and [modulo](/en/arithmetic/operation-on-number#modulus) to find the factorization of a number. Here is an example of its implementation: + +:::tabs key:lang +== Javascript + +```js +function factorize(number) { + let factor = 2; + let factors = []; + while (number > 1) { + if (number % factor === 0) { + factors.push(factor); + number /= factor; + } else { + factor++; + } + } + return factors; +} + +let factorize100 = factorize(100); // [2, 2, 5, 5] +``` + +== Kotlin + +```kt +fun factorize(number: Int): List { + var factor = 2 + val factors = mutableListOf() + var number = number + while (number > 1) { + if (number % factor == 0) { + factors.add(factor) + number /= factor + } else { + factor++ + } + } + return factors +} + +val factorize100 = factorize(100) // [2, 2, 5, 5] +``` + +== C++ + +```cpp +#include +#include + +std::vector factorize(int number) { + int factor = 2; + std::vector factors; + while (number > 1) { + if (number % factor == 0) { + factors.push_back(factor); + number /= factor; + } else { + factor++; + } + } + return factors; +} + +int main() { + std::vector factorize100 = factorize(100); // [2, 2, 5, 5] + return 0; +} +``` +== Python +```python +def factorize(number): + factor = 2 + factors = [] + while number > 1: + if number % factor == 0: + factors.append(factor) + number /= factor + else: + factor += 1 + + return factors + +factorize100 = factorize(100) # [2, 2, 5, 5] +``` + +::: + +Btw, what we use above `/=` is the same as `number = number / factor`, it's similar to `+= -= *=` we usually use. + + +## Multiples + +A multiple is the result of multiplying a number by another number. For example, if you have a number $a$ and multiply it by $n$ (which can be positive, negative, or zero), the result is a multiple of $a$. + +For example, if $a = 3$ then the multiples of 3 are: +- $3 \times 1 = 3$ +- $3 \times 2 = 6$ +- $3 \times 3 = 9$ +- and so on... + +If multiples are implemented in programming, we can use _loop_ to perform repeated multiplication. Here’s an example: +:::tabs key:lang +== Javascript + +```js +function multiples(a, n) { + let multiples = []; + for (let i = 1; i <= n; i++) { + multiples.push(a * i); + } + return multiples; +} + +let multiplesOf3 = multiples(3, 5); // [3, 6, 9, 12, 15] +``` +== Kotlin + +```kt +fun multiples(a: Int, n: Int): List { + val multiples = mutableListOf() + for (i in 1..n) { + multiples.add(a * i) + } + return multiples +} + +val multiplesOf3 = multiples(3, 5) // [3, 6, 9, 12, 15] +``` +== C++ + +```cpp +std::vector multiples(int a, int n) { + std::vector multiples; + for (int i = 1; i <= n; i++) { + multiples.push_back(a * i); + } + return multiples; +} + +int main() { + std::vector multiplesOf3 = multiples(3, 5); // [3, 6, 9, 12, 15] + return 0; +} +``` +== Python +```python +def multiples(a, n): + multiples = [] + for i in range(1, n+1): + multiples.append(a * i) + + return multiples + +multiplesOf3 = multiples(3, 5) # [3, 6, 9, 12, 15] +``` +::: + +## Greatest Common Factor (GCF) + +GCF is the largest number that can divide two numbers without a remainder. GCF is usually used to find the similarity of two different numbers. + +Now to find the GCF we can start by finding the factorization of the two numbers, then we look for the same factors of the two numbers. For example, if we want to find the GCF of 12 and 18, we can do it like this: + +$12 = 1,2,3,4,6,12$ + +$18 = 1,2,3,6,9,18$ + +We can see that the numbers that are common to both 12 and 18 are $1, 2, 3, \text{and } 6$. Now from these numbers we can take the largest one, which is 6. So the GCF of 12 and 18 is **$6$**. + +Another way is to use the Euclidean algorithm, the formula for which is: + +$$\text{GCF}(a, b) = \text{GCF}(b, a \mod b)$$ + +How to calculate it is like this: +1. Take two numbers $a$ and $b$. +2. Divide $a$ with $b$ and save the remainder (modulus), for example $r = a \mod b$. +3. Change $a$ with $b$ and $b$ with $r$. +4. Repeat steps 2 and 3 the rest ($r$) becomes 0. +5. If $r$ is 0, then the GCF of $a$ and $b$ is $b$. + +Are you still with me? Relax, let's turn it into code that we can easily understand: +:::tabs key:lang +== Javascript + +```javascript +function gcf(a, b) { + while (b !== 0) { + let t = b; + b = a % b; + a = t; + } + return a; +} + +let gcf1218 = gcf(12, 18); // 6 +``` +== Kotlin + +```kotlin +fun gcf(a: Int, b: Int): Int { + var a = a + var b = b + while (b != 0) { + val t = b + b = a % b + a = t + } + return a +} + +val gcf1218 = gcf(12, 18) // 6 +``` +== C++ + +```cpp +std::vector gcf(int a, int b) { + while (b != 0) { + int t = b; + b = a % b; + a = t; + } + return a; +} + +int main() { + int gcf1218 = gcf(12, 18); // 6 + return 0; +} +``` +== Python +```python +def gcf(a, b): + while b != 0: + t = b + b = a % b + a = t + + return a + +gcf1218 = gcf(12, 18) # 6 +``` +::: + + +## Least Common Multiple (LCM) + +The Least Common Multiple (LCM) is the smallest number that can be divided evenly by two numbers. For example, the LCM of 12 and 18 is **$36$**, because 36 is the smallest number that can be divided evenly by both numbers. + +Don't believe it? let's count $12 \times 3 = 36$ and $18 \times 2 = 36$. + +To find the LCM, we can use this formula: + +$$\text{LCM}(a, b) = \frac{a \times b}{\text{GCF}(a, b)}$$ + +If simulated, it would be like this: + +1. we have the GCF of 12 and 18 which is 6. +2. $12 \times 18 = 216$ (quite big) +3. $216 \div 6 = 36$ (this is the LCM) + +Or if you to complicate things, we can calculate manually by finding the multiples of both numbers. For example, if we want to find the LCM of 12 and 18, we can do it like this: + +| Number | Multiples of 1 | Multiples of 2 | Multiples of 3 | Multiples of $n$ | +|----------|-------------|-------------|-------------|---------------| +| 12 | 12 | 24 | 36 | ... | +| 18 | 18 | 36 | 54 | ... | + +From the table above we can see that the common multiple of 12 and 18 is **$36$**. +You are free to use whichever one you like, as long as it's not wrong. + +Easy right? Let's turn it into code that we can easily understand:: +:::tabs key:lang +== Javascript + +```javascript +function lcm(a, b) { + return (a * b) / gcf(a, b); +} + +let lcm1218 = lcm(12, 18); // 36 +``` +== Kotlin + +```kotlin +fun lcm(a: Int, b: Int): Int { + return (a * b) / gcf(a, b) +} + +val lcm1218 = lcm(12, 18) // 36 +``` +== C++ + +```cpp +int lcm(int a, int b) { + return (a * b) / gcf(a, b); +} + +int main() { + int lcm1218 = lcm(12, 18); // 36 + return 0; +} +``` +== Python +```python +def lcm(a, b): + return (a * b) / gcf(a, b) + +lcm1218 = lcm(12, 18) # 36.0 +``` +::: + + diff --git a/docs/en/arithmetic/numbers.md b/docs/en/arithmetic/numbers.md new file mode 100644 index 0000000..465af47 --- /dev/null +++ b/docs/en/arithmetic/numbers.md @@ -0,0 +1,148 @@ +--- +title: Numbers +description: Example of using Numbers in programming +--- + +# Numbers + +Numbers are the foundation of mathematics, everything in math uses numbers. In programming, numbers are also very important. We can perform various mathematical operations with numbers, such as addition, subtraction, multiplication, and division. + +However, numbers in programming are categorized into several types, depending on their data type. So, the use of numbers in programming will be slightly different from standard mathematics. Let's learn more about it! + +## Integers + +Integers are numbers without decimals. In programming, integers are usually referred to as `integer`. Examples of integers include 1, 2, 3, 4, 5, and so on. + +:::tabs key:lang +== Javascript +```js +let myInteger = 10; +``` +== Kotlin +```kt +val myInteger: Int = 10 +``` +== C++ +```cpp +int myInteger = 10; +``` +== Python +```python +myInteger = 10 +``` +::: + +Although it seems simple, don't forget that in programming, numbers have limits! For example, in JavaScript, the largest number you can use is **`9,007,199,254,740,992`**. That's equivalent to a very large number. I even have trouble saying it, seriously. + +Now, in C++ and other languages that have more data types than JS (which only has `number` and `BigInt`), the limits depend on the data type you use. For example, if you use `short` in C++, you can reach the number **`32,767`** except in Python, which doesn't have a limit for integers, as Python dynamically handles the size of integers. Here's an example: + +:::tabs key:lang +== Javascript + +| Data Type | Size (bits) | Minimum | Maximum | Maximum (Explicitly) | +|-----------|------------------|---------------|----|---------------------------| +| Number | 64 | -9,007,199,254,740,991
(−253 - 1) | 9,007,199,254,740,992
(253 - 1 ) | 18,446,744,073,709,551,616 (264) | +| BigInt | max 1,000,000,000 | `depends on memory` | `depends on memory` | `depends on memory` | +== C++ +| Data Type | Size (bits | Minimum | Maximum | Maximum (Explicitly) | +|-----------|------------------|------------------------------------------------|-----------------------------------------------|---------------------------| +| `short` | 16 | -32,768 | 32,767 | 65,536 (216) | +| `int` | 32 | -2,147,483,648 (-231) | 2,147,483,647 (231 - 1) | 4,294,687,296 (232) | +| `long` | 64 | -9,223,372,036,854,775,808 (-263) | 9,223,372,036,854,775,807 (263 - 1) | 18,446,744,073,709,551,616 (264) | +| `long long` | 64 | -9,223,372,036,854,775,808 (-263) | 9,223,372,036,854,775,807 (263 - 1) | 18,446,744,073,709,551,616 (264) | + +There are many more details which [you can check here](https://learn.microsoft.com/en-us/cpp/c-language/cpp-integer-limits?view=msvc-170#limits-on-integer-constants) +== Kotlin +| Data Type | Size (bits | Minimum | Maximum | Maximum (Explicitly) | +|-----------|------------------|------------------------------------------------|-----------------------------------------------|---------------------------| +| `Byte` | 8 | -128 | 127 | 256 (28) +| `Short` | 16 | -32,768 | 32,767 | 65,536 (216) | +| `Int` | 32 | -2,147,483,648 (-231) | 2,147,483,647 (231 - 1) | 4,294,687,296 (232) | +| `Long` | 64 | -9,223,372,036,854,775,808 (-263) | 9,223,372,036,854,775,807 (263 - 1) | 18,446,744,073,709,551,616 (264) | +::: + +## Decimal Numbers (Floating Point) + +Decimal numbers or floating points are numbers that have decimals. In programming, decimal numbers are usually referred to as `float` or `double`. Examples of decimal numbers include 1.5, 2.3, 3.14, and so on. To create a decimal number, you can use code like the following + +:::tabs key:lang +== Javascript +```js +let myDecimal = 3.14; +``` +== Kotlin +```kt +val myDecimal: Float = 3.14F +``` +We can also use `double` for decimal numbers that have more digits after the decimal point (up to 15 digits). Here's an example: +```kt +val myDecimal: Double = 3.141592653589793f +``` +== C++ +```cpp +float myDecimal = 3.14f; +``` +We can also use `double` for decimal numbers that have more digits after the decimal point (up to 15 digits). Here's an example: +```cpp +double myDecimal = 3.141592653589793F; +``` +== Python +```python +myDecimal = 3.14 +``` +::: + + +## Fractional Numbers + +Fractional numbers are numbers that have a numerator and a denominator. In programming, fractional numbers are usually referred to as `fraction`. Examples of fractional numbers include 1/2, 3/4, 5/6, and so on. Unfortunately, programming does not have a data type for fractional numbers. They are simply computed, resulting in a decimal number. An example of its use is as follows: + +:::tabs key:lang +== Javascript +```js +let myFraction = 1/2; +``` +== Kotlin +```kt +val myFraction = 1/2 // Automatically converted to float +``` +== C++ +```cpp +float myFraction = 1/2; +``` +== Python +```python +myFraction = 1/2 +``` +::: + +> [!WARNING] Caution when performing operations with fractional and decimal numbers +> In many programming languages, including JavaScript, there is something called `floating point error`, which can cause calculation results for decimal numbers to be inaccurate. This happens because decimal numbers cannot always be precisely represented in binary format. +> +> For example, when we add 0.1 and 0.2 in JavaScript, the result is not 0.3, but rather 0.30000000000000004. This is due to the limitations of decimal number representation in computers. +> +> To avoid this issue, it is recommended to limit the precision of calculation results by rounding to the desired number of decimal places (for instance, using `toFixed()` or `Math.round()`. +> +> You can also use libraries like BigNumber or others. + +What about **mixed fractions**? In mathematics, there's something like $1\frac{1}{2}$, and you can do it in programming too. You can use `float` or `double` for mixed fractions. An example of its use is as follows: +:::tabs key:lang +== Javascript +```js +let mixedFraction = 1 + 1/2; +``` +== Kotlin +```kt +val mixedFraction: Double = 1 + 1/2 +``` +== C++ +```cpp +double mixedFraction = 1 + 1/2; +``` +== Python +```python +mixedFraction = 1 + 1/2 +``` +::: + +Why addition? Because mixed fractions can actually be converted to regular decimal numbers. For example, $1\frac{1}{2}$ can be converted to $1 + \frac{1}{2}$, which is equal to $1.5$. diff --git a/docs/en/arithmetic/operation-on-number.md b/docs/en/arithmetic/operation-on-number.md new file mode 100644 index 0000000..ac6c694 --- /dev/null +++ b/docs/en/arithmetic/operation-on-number.md @@ -0,0 +1,236 @@ +--- +title: Operations on Number +description: Examples of using mathematical operations on numbers in programming +--- + +# Operation on Numbers + +Number operations or the processes of manipulating certain numeric values ​​using mathematical techniques such as addition, subtraction, multiplication, division, and more. In programming we cannot be separated from what is called number operations because the computer itself runs based on number operations. Here we will discuss number operations that are often used in programming. + +## Basic Operation + +In programming, we can perform various mathematical operations with numbers. There are addition, subtraction, multiplication, and division. Unlike regular mathematics that uses the symbols `+`, `-`, `*`, and `/`, in programming we use different symbols. An example of its use is as follows: + +:::tabs key:lang +== Javascript +```js +let a = 10; +let b = 5; +let additionResult = a + b; // 15 +let subtractionResult = a - b; // 5 +let multiplicationResult = a * b; // 50 +let divisionResult = a / b; // 2 +``` +== Kotlin +```kt +val a = 10 +val b = 5 +val additionResult = a + b // 15 +val subtractionResult = a - b // 5 +val multiplicationResult = a * b // 50 +val divisionResult = a / b // 2 +``` +== C++ +```cpp +int a = 10; +int b = 5; +int additionResult = a + b; // 15 +int subtractionResult = a - b; // 5 +int multiplicationResult = a * b; // 50 +int divisionResult = a / b; // 2 +``` +== Python +```python +a = 10 +b = 5 +additionResult = a + b # 15 +subtractionResult = a - b # 5 +multiplicationResult = a * b # 50 +divisionResult = a / b # 2 +``` +::: + +Above we use `/` for division and `*` for multiplication. This is because in programming, we cannot use mathematical symbols `÷` and `×` like the usual especially `.` because programming languages ​​generally follow ASCII rules that only support basic characters, so special mathematical symbols such as `÷` and `×` are not available. Instead, programming uses `*` as the replacement for multiplication and `/` as the replacement for division so that the code can run properly. + +> [!NOTE] +> Try checking your laptop or PC keyboard, is there `÷` and `×` symbols? (not this x). Most of the time, they don't exist, and that's one of the main reasons why programming doesn't use those symbols. :grin: + +## Exponentiation (Powers) + +Exponentiation is a mathematical operation used to multiply a number by itself $n$ times. In programming, you can use the `**` operator or the `pow()` to calculate powers. Here's an example: +:::tabs key:lang +== Javascript +```js +let power = 2 ** 3; // 8 +let power2 = Math.pow(2, 3); // 8 +``` +== Kotlin +```kt +val power = 2.0.pow(3) // 8.0 +val power2 = Math.pow(2.0, 3.0) // 8.0 +``` +== C++ +```cpp +#include +#include + +int main() { + double power = pow(2, 3); // 8 + double power2 = pow(2.0, 3.0); // 8 + return 0; +} +``` +== Python +```python +power = 2 ** 3 # 8 +power2 = pow(2, 3) # 8 +``` +::: + +`pow()` usually takes two parameters, where the first parameter is the base and the second parameter is the exponent. So to calculate $2^3$, we can write it as `pow(2, 3)`. + +## Roots + +Most programming languages have a function for calculating roots. In JavaScript, we can use the `Math.sqrt()` (*Square Root*) function for square roots. Here's an example: + +:::tabs key:lang +== Javascript +```js +let root = Math.sqrt(16); // 4 +``` + +== Kotlin +In Kotlin, we can use the `Math.sqrt()` function. Here's an example: +```kt +val root = Math.sqrt(16.0) // 4.0 +``` + +== C++ +In C++, we can use the `sqrt()` function from `cmath` library. Here's an example: +```cpp +#include +#include + +int main() { + double root = sqrt(16); // 4 + std::cout << root << std::endl; + return 0; +} +``` + +== Python +In Python, we can use the `sqrt()` function from `math` library. Here's an example: +```python +import math +root = math.sqrt(16) # 4.0 +``` +::: + +But there's a problem, if we want to calculate roots that are more than 2, like $\sqrt[3]{8}$ or $\sqrt[4]{16}$, Well, in this case, we can just raise the number to the power of $1/n$ where $n$ is the root we want. Here's an example: + +:::tabs key:lang +== Javascript +```js +let cubeRoot = Math.pow(8, 1/3); // 2 +let fourthRoot = Math.pow(16, 1/4); // 2 +``` +== Kotlin +```kt +val cubeRoot = Math.pow(8.0, 1.0/3.0) // 2.0 +val fourthRoot = Math.pow(16.0, 1.0/4.0) // 2.0 +``` +== C++ +```cpp +#include +#include + +int main() { + double cubeRoot = pow(8, 1.0/3); // 2 + double fourthRoot = pow(16, 1.0/4); // 2 + std::cout << cubeRoot << std::endl; + std::cout << fourthRoot << std::endl; + return 0; +} +``` +== Python +```python +cubeRoot = pow(8, 1/3) # 2.0 +fourthRoot = pow(16, 1/4) # 2.0 +``` +::: + +This can happen because any number that has an exponent of $1/n$ will produce the root of the number. So if we want to calculate $\sqrt[3]{8}$ we can write it as `pow(8, 1/3)`. + +## Modulus + +The modulus (remainder) operation calculates the remainder of division between two numbers. For example, if you divide 10 by 3, the remainder result is 1. In programming, you can use the `%` operator to calculate the modulus. + +This operation is particularly useful for checking if a number is even, odd, or follows a specific pattern. Here's an example: + +:::tabs key:lang +== Javascript +```js +let modulusResult = 10 % 3; // 1 +``` +== Kotlin +```kt +val modulusResult = 10 % 3 // 1 +``` +== C++ +```cpp +int modulusResult = 10 % 3; // 1 +``` +== Python +```python +modulusResult = 10 % 3 # 1 +``` +::: + +## Order of Operations + +In math, there’s a rule called the order of operations, which dictates the order in which calculations are performed. This also applies to programming and follows the same order as in standard math. It’s called PEMDAS (Parentheses, Exponents, Multiplication and Division, Addition and Subtraction) so the order is as followings + +1. Parentheses $()$ +2. Exponents $x^y$ and Roots $\sqrt{x}$ +3. Multiplication $x \times y$, Division $x \div y$ and Modulus $x \% y$ +4. Addition $x + y$ and Subtraction $x - y$ + +For example, if we want to calculate $6 + 3 * (2^3 + \sqrt{16})$: + +1. **Parentheses**: Focus on the expression inside the parentheses $2^3 + \sqrt{16}$. +3. **Exponents (powers)**: Calculate $2^3$. +$$2^3 = 8$$ +5. **Roots**: Calculate $\sqrt{16}$. +$$\sqrt{16} = 4$$ +7. **Addition inside parentheses**: Now, solve the operation inside parentheses $2^3 + \sqrt{16}$. +$$8 + 4 = 12$$ +9. **Multiplication**: Proceed to the operation outside the brackets, which is $3 \times (2^3 + \sqrt{16})$. +$$3 \times 12 = 36$$ +11. **Final addition**: Finally, add $6 + 36$. +$$6 + 36 = 42$$ +So, the final result is **42**. + +In programming, the order of operations is handled by the language, so you don't need to worry about the wrong order of operations. You just need to be careful with the formula you are going to use. If we put the formula into the code, it will look like this. + +:::tabs key:lang +== Javascript +```js +let result = 6 + 3 * (2 ** 3 + Math.sqrt(16)); // 42 +``` +== Kotlin +```kt +val result = 6 + 3 * (2.0.pow(3) + Math.sqrt(16.0)) // 42.0 +``` + +== C++ +```cpp +int result = 6 + 3 * (pow(2, 3) + sqrt(16)); // 42 +``` +== Python +```python +import math +result = 6 + 3 * (pow(2,3) + math.sqrt(16)) # 42.0 +``` +::: + +## diff --git a/docs/en/arithmetic/percent.md b/docs/en/arithmetic/percent.md new file mode 100644 index 0000000..c207f3b --- /dev/null +++ b/docs/en/arithmetic/percent.md @@ -0,0 +1,113 @@ +# Percentage + +Have you ever received a discount when shopping? Usually, if you don't cross it out, you use a percentage sign ($\%$). Well, this percentage is how we measure how big or small a value is compared to its original value. + +For example, you buy clothes for $\$10$ but you get a $20\%$ discount, that means you can buy the clothes for $\$8$. + +How to calculate percentage vakue is very easy, we can use the formula: +$$ percentage\;value = \frac{original\;value}{100} \times percentage $$ + +So if we want to calculate $20\%$ from $\$10$ we can write it as: +$$ percentage\;value = \frac{10}{100} \times 20\% = 2 $$ + +because divided by $100$, we can subtract two zeros from $10$ which becomes $0.1$ and multiply it by $20$ to get $2$. + +If we convert it to code, we can write it like this: +:::tabs key:lang +== Javascript +```js +let price = 10; +let discount = 20; +let percentageValue = (price / 100) * discount; // 2 +``` +== Kotlin +```kt +val price = 10 +val discount = 20 +val percentageValue = (price / 100) * discount // 2 +``` +== C++ +```cpp +int price = 10; +int discount = 20; +int percentageValue = (price / 100) * discount; // 2 +``` +== Python +```python +price = 10 +discount = 20 +percentageValue = (price / 100) * discount # 2.0 +``` +::: + +## Finding True Value + +If previously we calculated the percentage of the original value, now we will find the original value of the percentage value. The method is simply to reverse the formula so: +$$ original\;value = \frac{percentage\;value}{percentage} \times 100 $$ + +For example, we have a percentage value of $2$ and we want to find the original value, we can write: +$$ original\;value = \frac{2}{20\%} \times 100 = 10 $$ + +If we convert it to code, we can write it like this: +:::tabs key:lang +== Javascript +```js +let percentageValue = 2; +let discount = 20; +let price = (percentageValue / discount) * 100; // 10 +``` +== Kotlin +```kt +val percentageValue = 2 +val discount = 20 +val price = (percentageValue / discount) * 100 // 10 +``` +== C++ +```cpp +int percentageValue = 2; +int discount = 20; +int price = (percentageValue / discount) * 100; // 10 +``` +== Python +```python +percentageValue = 2 +discount = 20 +price = (percentageValue / discount) * 100 # 10.0 + +``` +::: + +## Finding Percentage + +If previously we calculated the percentage of the original value, now we will find the percentage value of the original value. We change the formula to: +$$ percentage = \frac{original\;value}{percentage\;value} \times 100 $$ +For example, we have an original value of $10$ and we want to find the percentage, we can write: +$$ percentage = \frac{2}{10} \times 100 = 20\% $$ + +If we convert it to code, we can write it like this: +:::tabs key:lang +== Javascript +```js +let price = 10; +let discount = 2; +let percentage = (discount / price) * 100; // 20 +``` +== Kotlin +```kt +val price = 10 +val discount = 2 +val percentage = (discount / price) * 100 // 20 +``` +== C++ +```cpp +int price = 10; +int discount = 2; +int percentage = (discount / price) * 100; // 20 +``` +== Python +```python +harga = 10 +discount = 2 +percentage = (discount / price) * 100 # 20.0 +``` +::: diff --git a/docs/en/calculus/limit.md b/docs/en/calculus/limit.md new file mode 100644 index 0000000..d751936 --- /dev/null +++ b/docs/en/calculus/limit.md @@ -0,0 +1,246 @@ +# Limit +The limit is the value that a function approeches as its input value approaches some value. Limits are defined as + +$$\begin{align*} + \lim_{x \to a} f(x) = L +\end{align*}$$ + +We can understand the behavior of a function by just determine its limit of a certain point. We will know such function at that point is either continue, discontinue, or differentiable. + +## How to detemine the limit +Suppose a curve $f(x) = x+3$ and we will know limit value around $x=3$. We can approach by several point from lefthand side and righthand side. + + +| Left | Right | +| --------------------|---------------------| +|$f(2.9) = 5.9$ | $f(3.1) = 6.1$ | +|$f(2.99) = 5.99$ | $f(3.01) = 6.01$ | +|$f(2.99) = 5.999$ | $f(3.001) = 6.001$ | +| ... | ... | + +or with programming code: + +:::tabs key:lang +== Javascript +```js +function f(x){ + return x+3; +} + +function calculateLimit(point){ + //approaching from right + for(let i = 1; i<=10;i++){ + let y = f(point+1/(10**i)); + console.log(`f(${point+1/(10**i)})=${y}`); + } + //approaching from left + for(let i = 1; i<=10;i++){ + let y = f(point-1/(10**i)); + console.log(`f(${point-1/(10**i)})=${y}`); + } +} +calculateLimit(3); + +``` +== Kotlin +```kt +fun f(x: Double): Double { + return x + 3 +} + +fun calculateLimit(point: Double) { + // approaching from right + println("approaching from right:") + for (i in 1..10) { + val y = f(point + 1 / Math.pow(10.0, i.toDouble())) + println("f(${point + 1 / Math.pow(10.0, i.toDouble())}) = $y") + } + + // approaching from left + println("approaching from left:") + for (i in 1..10) { + val y = f(point - 1 / Math.pow(10.0, i.toDouble())) + println("f(${point - 1 / Math.pow(10.0, i.toDouble())}) = $y") + } +} + +fun main() { + calculateLimit(3.0) +} + +``` +== C++ +```cpp +#include +#include + +double f(double x) { + return x + 3; +} + +void calculateLimit(double point) { + // approaching from right + std::cout << "approaching from right:" << std::endl; + for (int i = 1; i <= 10; i++) { + double y = f(point + 1 / std::pow(10, i)); + std::cout << "f(" << (point + 1 / std::pow(10, i)) << ") = " << y << std::endl; + } + + // approaching from left + std::cout << "approaching from left:" << std::endl; + for (int i = 1; i <= 10; i++) { + double y = f(point - 1 / std::pow(10, i)); + std::cout << "f(" << (point - 1 / std::pow(10, i)) << ") = " << y << std::endl; + } +} + +int main() { + calculateLimit(3.0); + return 0; +} + +``` +== Python +```python +def f(x): + return x + 3 + +def calculate_limit(point): + # approaching from right + print("approaching from right:") + for i in range(1, 11): + y = f(point + 1 / (10 ** i)) + print(f"f({point + 1 / (10 ** i)}) = {y}") + + # approaching from left + print("approaching from left:") + for i in range(1, 11): + y = f(point - 1 / (10 ** i)) + print(f"f({point - 1 / (10 ** i)}) = {y}") + +# Run the calculation +calculate_limit(3) + +``` +::: + +From that we can conclude either approaching from left or right, all the values are tend to $6$. Hence the limit of the function in $x=3$ is $6$. At once the result is identical with when we straightly give $x=3$ input to that function. However there is a speciality from the limit that we can still determine the limit value even the function is undefined at certain point. For instance, +let's suppose another function that similiar to the $f(x)=x+3$, let's take $g(x)=\frac{x^2-9}{x-3}$ + + + +(please try clicking $x=3$) on bare eyes the curve is strongly similar with $f(x)=x+3$, but actually undefined at $x=3$. Now, we try calculate the limit + +| Kiri | Kanan | +| --------------------|---------------------| +|$f(2.9) = 5.9$ | $f(3.1) = 6.1$ | +|$f(2.99) = 5.99$ | $f(3.01) = 6.01$ | +|$f(2.99) = 5.999$ | $f(3.001) = 6.001$ | +| ... | ... | + +code: +:::tabs key:lang +== Javascript +```js +function f(x){ + return (x**2-9)/(x-3); +} + +function calculateLimit(point){ + // approaching from right + for(let i = 1; i<=10;i++){ + let y = f(point+1/(10**i)); + console.log(`f(${point+1/(10**i)})=${y}`); + } + // approaching from left + for(let i = 1; i<=10;i++){ + let y = f(point-1/(10**i)); + console.log(`f(${point-1/(10**i)})=${y}`); + } +} +calculateLimit(3); + +``` +== Kotlin +```kt +fun f(x: Double): Double { + return (x**2-9)/(x-3) +} + +fun calculateLimit(point: Double) { + // approaching from right + println("approaching from right:") + for (i in 1..10) { + val y = f(point + 1 / Math.pow(10.0, i.toDouble())) + println("f(${point + 1 / Math.pow(10.0, i.toDouble())}) = $y") + } + + // approaching from left + println("approaching from left:") + for (i in 1..10) { + val y = f(point - 1 / Math.pow(10.0, i.toDouble())) + println("f(${point - 1 / Math.pow(10.0, i.toDouble())}) = $y") + } +} + +fun main() { + calculateLimit(3.0) +} + +``` +== C++ +```cpp +#include +#include + +double f(double x) { + return (x**2-9)/(x-3); +} + +void calculateLimit(double point) { + // approaching from right + std::cout << "approaching from right:" << std::endl; + for (int i = 1; i <= 10; i++) { + double y = f(point + 1 / std::pow(10, i)); + std::cout << "f(" << (point + 1 / std::pow(10, i)) << ") = " << y << std::endl; + } + + // approaching from left + std::cout << "approaching from left:" << std::endl; + for (int i = 1; i <= 10; i++) { + double y = f(point - 1 / std::pow(10, i)); + std::cout << "f(" << (point - 1 / std::pow(10, i)) << ") = " << y << std::endl; + } +} + +int main() { + calculateLimit(3.0); + return 0; +} + +``` +== Python +```python +def f(x): + return (x**2-9)/(x-3) + +def calculate_limit(point): + # approaching from right + print("approaching from right:") + for i in range(1, 11): + y = f(point + 1 / (10 ** i)) + print(f"f({point + 1 / (10 ** i)}) = {y}") + + # approaching from left + print("approaching from left:") + for i in range(1, 11): + y = f(point - 1 / (10 ** i)) + print(f"f({point - 1 / (10 ** i)}) = {y}") + +# Run the calculation +calculate_limit(3) + +``` +::: + +Thus we can conclude that determining the limit value is not affected by the value of the function. \ No newline at end of file diff --git a/docs/en/guide/index.md b/docs/en/guide/index.md new file mode 100644 index 0000000..6aacbaf --- /dev/null +++ b/docs/en/guide/index.md @@ -0,0 +1,39 @@ +# Learning Guide + +Before you begin, there are a few important things you need to know. **Math W Code** is a place to learn and share about mathematics with the help of programming languages. Here, you can learn while also contributing to the development of mathematical knowledge through code! + +## Requirements + +Our focus is on how mathematical concepts are applied in programming. Therefore, we will not discuss things like how to install a code editor, write basic code, and so on, however we will cover some basic programming concepts. + +So, before you start, we hope you already understand the basic of programming, you don't need to be very good at it though. But it's important that you can understand the codes we will discuss. + +## Programming Languages + +In this site, we will use various programming languages to explain mathematical concepts. Some of the languages ​​we will use are: + +
+
+ Javascript +
+
+ C++ +
+
+ Kotlin +
+
+ Python +
+
+ +Each language has its own unique way of handling mathematics. So, get ready to explore many new things on this learning journey! + +In some materials, the programming language mentioned may not be available. + +Don’t worry, you can still follow the concepts taught in other languages that are available. The concepts aren't too different, after all. The key is to focus on the implementation, okay! + +> [!NOTE] +> In some materials, the programming language mentioned may not be available. +> +> Don’t worry, you can still follow the concepts taught in other languages that are available. The concepts aren't too different, after all. The key is to focus on the implementation, okay! diff --git a/docs/en/index.md b/docs/en/index.md new file mode 100644 index 0000000..f340e54 --- /dev/null +++ b/docs/en/index.md @@ -0,0 +1,73 @@ +--- +# https://vitepress.dev/reference/default-theme-home-page +layout: home + +hero: + name: "Math With Code" + text: "Learn mathematics with lines of code" + tagline: Mathematics with a different approach + image: + src: /luca.webp + alt: Luca Math With Code + actions: + - theme: brand + text: Learn Now + link: /en/guide/ + - theme: alt + text: Contribute + link: https://github.com/xirf/mathwithcode +features: + - icon: 🔢 + title: Arithmetic + details: Numbers, Operations, Factors, Multiples and others + link: /en/arithmetic/numbers/ + linkText: Learn + - icon: 📐 + title: Algebra + details: Polynomials, Equations, Matrices, Determinants and others + link: /en/algebra/function/ + linkText: Learn + - icon: 📈 + title: Linear Algebra + details: Vectors, Vector Spaces, Orthogonality and others + link: /en/linear-algebra/linear-transformation + linkText: Learn + - icon: 📊 + title: Statistics + details: Data, Distribution, Regression, Hypothesis Testing and others + link: /en/statistics/measures-concentration-dispersion + linkText: Learn + - icon: 🔄️ + title: Calculus + details: Limit, Derivative, and Integration + link: /en/calculus/limit + linkText: Learn +--- + + + + + + diff --git a/docs/en/linear-algebra/linear-transformation.md b/docs/en/linear-algebra/linear-transformation.md new file mode 100644 index 0000000..400dea6 --- /dev/null +++ b/docs/en/linear-algebra/linear-transformation.md @@ -0,0 +1,413 @@ +--- +contributors: + - name: "Rijal" + username: "Rnov24" +--- +# Linear Transformation + +A linear transformation is a rule that maps each vector in one vector space to another vector in a possibly different vector space, +while preserving the operations of vector addition and scalar multiplication. +In other words, a linear transformation is a function that takes a vector as input and produces a vector as output, +subject to the following constraints: + +* **Additivity**: A transformation applied to the addition of two vectors produces the same result as the sum of the results of the transformation on each vector. +$$ +\mathbf{T}(\mathbf{u} + \mathbf{v}) = \mathbf{T}(\mathbf{u}) + \mathbf{T}(\mathbf{v}) +$$ +* **Homogeneity**: A transformation applied to a scalar multiple of a vector is the same as a scalar multiple of the transformation applied to that vector. +$$ +\mathbf{T}(c\mathbf{u}) = c\mathbf{T}(\mathbf{u}) +$$ + +# Types of Linear Transformations + +Linear transformations can be used to change a vector into another vector, such as enlarging, shrinking, or even changing the rotation of the vector. Here are some types of linear transformations: + +## Scaling + +We can use scalars to enlarge or reduce vectors. +$$ +\mathbf{u}= \begin{pmatrix}i \\ j \end{pmatrix} +$$ +$$ +\mathbf{T}(c\mathbf{u})= c \begin{pmatrix}i \\ j \end{pmatrix} = \begin{pmatrix}i \cdot c \\ j \cdot c \end{pmatrix} +$$ + +It can be implemented into a program, like the followings: +:::tabs key:lang +== JavaScript +``` js +function scaling(vector, scalar) { + let result = []; + for (let i = 0; i < vector.length; i++) { + result.push(vector[i] * scalar); + } + return result; +} + +// example usage +let vector = [2, 3]; +let scalar = 2; +let result = scaling(vector, scalar); +console.log(result); // output: [4, 6] +``` +== C++ +``` cpp +#include +#include + +void scaling(double vector[], double scalar) { + double resultVector[sizeof(vector) / sizeof(vector[0])]; + for (int i = 0; i < sizeof(vector) / sizeof(vector[0]); i++) { + resultVector[i] = vector[i] * scalar; + } + std::cout << "The result of scaling vector [" << vector[0] << ", " << vector[1] << "] with scalar " << scalar << " is [" << resultVector[0] << ", " << resultVector[1] << "]" << std::endl; +} + +int main() { + double vector[] = {2, 3}; + double scalar = 2; + + scaling(vector, scalar); // Output: [4, 6] + return 0; +} +``` +== Kotlin +``` kotlin +fun scaling(vector: List, scalar: Int): List { + val result = mutableListOf() + for (value in vector) { + result.add(value * scalar) + } + return result +} + +// example usage +fun main() { + val vector = listOf(2, 3) + val scalar = 2 + val result = scaling(vector, scalar) + println(result) // output: [4, 6] +} +``` +== Python +``` py +def scaling(vector, scalar): + result = [] + for i in range(len(vector)): + result.append(vector[i] * scalar) + return result + +# example usage +vector = [2, 3] +scalar = 2 +result = scaling(vector, scalar) +print(result) # output: [4, 6] +``` +::: + +## Rotation + +We can rotate a vector by multiplying it by a rotation matrix $R(\theta)$, where $\theta$ is the rotation angle of the vector. +$$ +R(\theta) = \begin{pmatrix} \cos\theta & -\sin\theta \\ \sin\theta & \cos\theta \end{pmatrix} +$$ +$$ +R(\theta)u = \begin{pmatrix} \cos\theta & -\sin\theta \\ \sin\theta & \cos\theta \end{pmatrix} \begin{pmatrix}i \\ j \end{pmatrix}= \begin{pmatrix} i\cos\theta - j\sin\theta \\ i\sin\theta + j\cos\theta \end{pmatrix} +$$ + +It can be implemented into a program, like the followings: +:::tabs key:lang +== JavaScript +``` js +function rotation(vector, theta) { + // Initialize array to store the rotation result + let result = []; + + // Calculate the cosine and sine of the angle theta + let cosTheta = Math.cos(theta); + let sinTheta = Math.sin(theta); + + // Perform rotation calculation for i and j components + result.push(vector[0] * cosTheta - vector[1] * sinTheta); // i component + result.push(vector[0] * sinTheta + vector[1] * cosTheta); // j component + + // Return rotation result + return result; +} + +// example usage +let vector = [2, 3]; +let theta = Math.PI / 2; // 90 degrees +let result = rotation(vector, theta); +console.log(result); // expected output: [-3, 2] +``` +== C++ +``` cpp +#include +#include + +void rotation(double vector[], double theta, double result[]) { + // Calculate cosine and sine of the angle theta + double cosTheta = std::cos(theta); + double sinTheta = std::sin(theta); + + // Perform rotation calculation for i and j components + result[0] = vector[0] * cosTheta - vector[1] * sinTheta; // i component + result[1] = vector[0] * sinTheta + vector[1] * cosTheta; // j component +} + +int main() { + double vector[] = {2, 3}; + double theta = M_PI / 2; // 90 degrees + double result[2]; + + rotation(vector, theta, result); + std::cout << "(" << result[0] << ", " << result[1] << ")" << std::endl; // expected output: (-3, 2) + + return 0; +} +``` +== Kotlin +``` kotlin +import kotlin.math.cos +import kotlin.math.sin +import kotlin.math.PI + +fun rotation(vector: List, theta: Double): List { + // Calculate the cosine and sine of the angle theta + val cosTheta = cos(theta) + val sinTheta = sin(theta) + + // Perform rotation calculation for i and j components + val iComponent = vector[0] * cosTheta - vector[1] * sinTheta + val jComponent = vector[0] * sinTheta + vector[1] * cosTheta + + // Return rotation result + return listOf(iComponent, jComponent) +} + +// example usage +fun main() { + val vector = listOf(2.0, 3.0) + val theta = PI / 2 // 90 degrees + val result = rotation(vector, theta) + println(result) // expected output: [-3.0, 2.0] +} +``` +== Python +``` py +import math + +def rotasi(vector, theta): + # Inisialisasi array untuk menyimpan hasil rotasi + hasil = [] + + # Hitung cosinus dan sinus dari sudut theta + cosTheta = math.cos(theta) + sinTheta = math.sin(theta) + + # Lakukan perhitungan rotasi untuk komponen i dan j + hasil.append(vector[0] * cosTheta - vector[1] * sinTheta) # Komponen i + hasil.append(vector[0] * sinTheta + vector[1] * cosTheta) # Komponen j + + # Return hasil rotasi + return hasil + +# contoh penggunaan +vector = [2, 3] +theta = math.pi / 2 # 90 derajat +result = rotasi(vector, theta) +print(result) + +``` +::: + +## Shifting + +We can perform shearing to make a vector appear shifted or distorted by multiplying it with a shearing matrix \( S(a, b) \), where \( a \) and \( b \) are the shearing parameters. Set \( b = 0 \) for horizontal shearing or \( a = 0 \) for vertical shearing, or combine both for diagonal shearing. + +$$ +S(a, b) = \begin{pmatrix} 1 & a \\ b & 1 \end{pmatrix} +$$ +$$ +S(a, b)u = \begin{pmatrix} 1 & a \\ b & 1 \end{pmatrix} \begin{pmatrix} i \\ j \end{pmatrix} = \begin{pmatrix} i + aj \\ bi + j \end{pmatrix} +$$ + +This can be implemented in a program as follows: + +:::tabs key:lang +== JavaScript +``` js +function shear(vector, a, b) { + // Calculate the shearing result + let result = [vector[0] * 1 + a * vector[1], b * vector[0] + vector[1] * 1]; + return result; +} + +// example usage +let vector = [2, 3]; +let a = 1; // horizontal shearing parameter +let b = 0; // vertical shearing parameter +let result = shear(vector, a, b); +console.log(result); // expected output: [5, 3] +``` +== C++ +``` cpp +#include +#include + +std::vector shear(const std::vector& vector, double a, double b) { + // Calculate the shearing result + std::vector result = {vector[0] * 1 + a * vector[1], b * vector[0] + vector[1] * 1}; + return result; +} + +int main() { + // example usage + std::vector vector = {2, 3}; + double a = 1; // horizontal shearing parameter + double b = 0; // vertical shearing parameter + std::vector result = shear(vector, a, b); + std::cout << "(" << result[0] << ", " << result[1] << ")" << std::endl; // expected output: (5, 3) + return 0; +} +``` +== Kotlin +``` kotlin +fun shear(vector: List, a: Double, b: Double): List { + // Calculate the shearing result + val iComponent = vector[0] * 1 + a * vector[1] + val jComponent = b * vector[0] + vector[1] * 1 + return listOf(iComponent, jComponent) +} + +// example usage +fun main() { + val vector = listOf(2.0, 3.0) + val a = 1.0 // horizontal shearing parameter + val b = 0.0 // vertical shearing parameter + val result = shear(vector, a, b) + println(result) // expected output: [5.0, 3.0] +} +``` +== Python +``` py +def shear(vector, a, b): + # Calculate the shearing result + result = [vector[0] * 1 + a * vector[1], b * vector[0] + vector[1] * 1] + return result + +# example usage +vector = [2, 3] +a = 1 # horizontal shearing parameter +b = 0 # vertical shearing parameter +result = shear(vector, a, b) +print(result) # expected output: [5, 3] +``` +::: + + +## Reflection + +We can perform a reflection to make a vector appear as a mirror image by multiplying it with a reflection matrix \( F(x, y) \), where \( x \) and \( y \) are the reflection parameters. Set \( x = -1 \) for horizontal reflection or \( y = -1 \) for vertical reflection, or combine both for a diagonal reflection. + +* Reflection across the x-axis: +$$ +R_xu = \begin{pmatrix} 1 & 0 \\ 0 & -1 \end{pmatrix} \begin{pmatrix} i \\ j \end{pmatrix} = \begin{pmatrix} i \\ -j \end{pmatrix} +$$ +* Reflection across the y-axis: +$$ +R_yu = \begin{pmatrix} -1 & 0 \\ 0 & 1 \end{pmatrix} \begin{pmatrix} i \\ j \end{pmatrix} = \begin{pmatrix} -i \\ j \end{pmatrix} +$$ + +This can be implemented in a program as follows: + +:::tabs key:lang +== JavaScript +``` js +function reflect(vector, axis) { + let result; + if (axis === "x") { + result = [vector[0], -vector[1]]; + } else if (axis === "y") { + result = [-vector[0], vector[1]]; + } + return result; +} + +// example usage +let vector = [2, 3]; +let result = reflect(vector, "x"); // or reflect(vector, "y") for reflection across y-axis +console.log(result); // expected output: [2, -3] or [-2, 3] +``` +== C++ +```cpp +#include + +void reflect(const double vector[], const char axis, double result[]) { + if (axis == 'x') { + result[0] = vector[0]; + result[1] = -vector[1]; + } else if (axis == 'y') { + result[0] = -vector[0]; + result[1] = vector[1]; + } +} + +int main() { + double vector[] = {2, 3}; + char axis = 'x'; // 'x' for reflection across x-axis, 'y' for reflection across y-axis + double result[2]; + + reflect(vector, axis, result); + std::cout << "Reflection of vector [" << vector[0] << ", " << vector[1] << "] across "; + if (axis == 'x') { + std::cout << "x-axis is [" << result[0] << ", " << result[1] << "]" << std::endl; // expected output: (2, -3) + } else if (axis == 'y') { + std::cout << "y-axis is [" << result[0] << ", " << result[1] << "]" << std::endl; // expected output: (-2, 3) + } + + return 0; +} +``` +== Kotlin +``` kotlin +fun reflect(vector: List, axis: String): List { + return if (axis == "x") { + listOf(vector[0], -vector[1]) + } else if (axis == "y") { + listOf(-vector[0], vector[1]) + } else { + vector // return the original vector if axis is not x or y + } +} + +// example usage +fun main() { + val vector = listOf(2.0, 3.0) + val axis = "x" // "x" for reflection across x-axis, "y" for reflection across y-axis + val result = reflect(vector, axis) + println(result) // expected output: [2.0, -3.0] or [-2.0, 3.0] +} +``` +== Python +``` py +def reflect(vector, axis): + if axis == "x": + result = [vector[0], -vector[1]] + elif axis == "y": + result = [-vector[0], vector[1]] + return result + +# example usage +vector = [2, 3] +axis = "x" # "x" for reflection across x-axis, "y" for reflection across y-axis +result = reflect(vector, axis) +print(result) # expected output: [2, -3] or [-2, 3] +``` +::: + +::: info +In fact, all the transformations mentioned here are examples of linear transformations. Linear transformations allow for creating custom transformation matrices, as long as they adhere to the rules of Additivity, Homogeneity, and Matrix Multiplication. +::: diff --git a/docs/en/linear-algebra/matrix-multiplication.md b/docs/en/linear-algebra/matrix-multiplication.md new file mode 100644 index 0000000..8155760 --- /dev/null +++ b/docs/en/linear-algebra/matrix-multiplication.md @@ -0,0 +1,265 @@ +--- +contributors: + - name: "Rijal" + username: "Rnov24" +--- +# Matrix Multiplication +Matrix multiplication is a mathematical operation used to combine two matrices by multiplying their corresponding elements. +The result of matrix multiplication is a new matrix that has the same number of rows as the first matrix and the same number of columns as the second matrix. + +## Rules of Matrix Multiplication + +Here are the rules for matrix multiplication: + +* The number of rows of the first matrix must be equal to the number of columns of the second matrix. +$$ +A ^{m\times n} \times B^{n \times p} +$$ +* The result of matrix multiplication is a new matrix with the same number of rows as the first matrix and the same number of columns as the second matrix. +$$ +A ^{m\times n} \times B^{n \times p} = AB^{m \times p} +$$ +* The elements of the matrix product are calculated by multiplying the corresponding elements of the first and second matrices, then adding the results. +$$ +\begin{bmatrix} +a_{11} & a_{12} & a_{13} \\ +a_{21} & a_{22} & a_{23} +\end{bmatrix} \times +\begin{bmatrix} +b_{11} & b_{12} \\ +b_{21} & b_{22} \\ +b_{31} & b_{32} +\end{bmatrix} = +\begin{bmatrix} +a_{11}*b_{11} + a_{12}*b_{21} + a_{13}*b_{31} & a_{11}*b_{12} + a_{12}*b_{22} + a_{13}*b_{32} \\ +a_{21}*b_{11} + a_{22}*b_{21} + a_{23}*b_{31} & a_{21}*b_{12} + a_{22}*b_{22} + a_{23}*b_{32} +\end{bmatrix} +$$ + +## Code examples and implementation +An example of a matrix multiplication problem is as follows: + +Given two matrices A and B of size 2x2 and 2x3, respectively: + +$$ +A = +\begin{bmatrix} +2 & 3 \\ +4 & 1 +\end{bmatrix} +$$ + +$$ +B = +\begin{bmatrix} +1 & 2 & 3 \\ +4 & 5 & 6 +\end{bmatrix} +$$ + +To solve the matrix multiplication above. Here are the steps: + +1. Multiply and sum the first row of matrix $A$ with the first column of matrix $B$. + $$ + 2 \times 1 + 3 \times 4 = 14 + $$ +2. Multiply and sum the first row of matrix $A$ with the second column of matrix $B$. + $$ + 2 \times 2 + 3 \times 5 = 19 + $$ +3. Multiply and sum the first row of matrix $A$ with the third column of matrix $B$. + $$ + 2 \times 3 + 3 \times 6 = 24 + $$ +4. Multiply and sum the second row of matrix $A$ with the first column of matrix $B$. + $$ + 4 \times 1 + 1 \times 4 = 8 + $$ +5. Multiply and sum the second row of matrix $A$ with the second column of matrix $B$. + $$ + 4 \times 2 + 1 \times 5 = 13 + $$ +6. Multiply and sum the second row of matrix $A$ with the third column of matrix $B$. + $$ + 4 \times 3 + 1 \times 6 = 18 + $$ +7. Place all elements in a new matrix. + $$ + AB = + \begin{bmatrix} + 14 & 19 & 24 \\ + 8 & 13 & 18 + \end{bmatrix} + $$ + +Below is the code implementation in multiple languages: + +:::tabs key:lang +== JavaScript +```js +// Initialize arrays for matrices and result +const A = [ + [2, 3], + [4, 1] +]; + +const B = [ + [1, 2, 3], + [4, 5, 6] +]; + +const result = []; + +// Perform matrix multiplication +for (let i = 0; i < A.length; i++) { + result[i] = []; + for (let j = 0; j < B[0].length; j++) { + // Initialize variable to store the sum of products for row A and column B + let sum = 0; + for (let k = 0; k < A[0].length; k++) { + // Multiply elements of row A by elements of column B and add to sum + sum += A[i][k] * B[k][j]; + } + // Store the result of multiplying row A by column B in result array + result[i][j] = sum; + } +} + +console.log(result); +``` +== C++ +```cpp +#include +#include + +int main() { + // Initialize matrices A and B + std::vector> A = {{2, 3}, {4, 1}}; + std::vector> B = {{1, 2, 3}, {4, 5, 6}}; + // Initialize result matrix to store the product of A and B + std::vector> result(A.size(), std::vector(B[0].size(), 0)); + + for (int i = 0; i < A.size(); i++) { + for (int j = 0; j < B[0].size(); j++) { + // Initialize sum to accumulate the product of elements in row A and column B + int sum = 0; + for (int k = 0; k < A[0].size(); k++) { + // Multiply elements of row A and column B, add to sum + sum += A[i][k] * B[k][j]; + } + // Store the result of row-by-column multiplication in result matrix + result[i][j] = sum; + } + } + + for (const auto& row : result) { + for (int val : row) { + std::cout << val << " "; + } + std::cout << std::endl; + } + + return 0; +} +``` +== Kotlin +``` kotlin +fun main() { + // Initialize matrices A and B + val A = arrayOf( + intArrayOf(2, 3), + intArrayOf(4, 1) + ) + + val B = arrayOf( + intArrayOf(1, 2, 3), + intArrayOf(4, 5, 6) + ) + + // Initialize result matrix to store the product of A and B + val result = Array(A.size) { IntArray(B[0].size) } + + for (i in A.indices) { + for (j in B[0].indices) { + // Initialize sum to accumulate the product of elements in row A and column B + var sum = 0 + for (k in A[0].indices) { + // Multiply elements of row A and column B, add to sum + sum += A[i][k] * B[k][j] + } + // Store the result of row-by-column multiplication in result matrix + result[i][j] = sum + } + } + + // Display the result matrix + for (row in result) { + println(row.joinToString(" ")) + } +} +``` +== Python +```py +# Initialize matrices A and B +A = [ + [2, 3], + [4, 1] +] + +B = [ + [1, 2, 3], + [4, 5, 6] +] + +# Initialize result matrix to store the product of A and B +result = [[0 for _ in range(len(B[0]))] for _ in range(len(A))] + +for i in range(len(A)): + for j in range(len(B[0])): + # Initialize sum to accumulate the product of elements in row A and column B + sum = 0 + for k in range(len(A[0])): + # Multiply elements of row A and column B, add to sum + sum += A[i][k] * B[k][j] + # Store the result of row-by-column multiplication in result matrix + result[i][j] = sum + +# Display the result matrix +for row in result: + for val in row: + print(val, end=" ") + print() +``` +::: + +For the Python programming language, there is a built-in operator for matrix multiplication, namely by using the symbol`@`. For example: +```py +# Initialize both matrices +A = [ + [2, 3], + [4, 1] +] + +B = [ + [1, 2, 3], + [4, 5, 6] +] + +# Multiple both matrices with @ +result = A @ B + +# Show multiplication result +for row in result: + for val in row: + print(val, end=" ") + print() +``` + +--- +Rijal +
+Instagram :[ ri.jalll ](https://www.instagram.com/ri.jalll) +
+Facebook: [ Rijal ](https://www.facebook.com/24rijal) + +--- diff --git a/docs/en/linear-algebra/vector.md b/docs/en/linear-algebra/vector.md new file mode 100644 index 0000000..e93e6fb --- /dev/null +++ b/docs/en/linear-algebra/vector.md @@ -0,0 +1 @@ +# Vector \ No newline at end of file diff --git a/docs/en/sponsors.md b/docs/en/sponsors.md new file mode 100644 index 0000000..acbafbd --- /dev/null +++ b/docs/en/sponsors.md @@ -0,0 +1,79 @@ +--- +layout: home +sidebar: false +ads: false +editLink: false +--- +
+
+ +# Support Math With Code + +## About Us + +Math With Code is an open-source math learning platform committed to providing quality education for free to everyone. We believe that mathematical knowledge should be accessible to anyone without financial barriers. + +## Why Become a Sponsor? + +By becoming a sponsor, you contribute to: + +- Ensuring that content remains free and ad-free +- Supporting the development of new learning materials +- Helping with operational costs (hosting, domain, etc.) +- Encouraging innovation in math education + +## How to Contribute + +### Financial Support + +Financial support can be given through: + +- [Github Sponsor](https://github.com/sponsors/xirf) +- [Patreon](https://patreon.com/xirf) +- [Trakteer](https://trakteer.id/xirf) (for users in Indonesia) + +### Non-Financial Support + +1. **Content Collaboration** + + - Writing articles or tutorials + - Creating educational videos + - Translating content + +2. **Technical Support** + + - Code review + - Bug fixing + - Infrastructure improvements + +3. **Marketing & Outreach** + - Promoting on social media + - Writing reviews + - Organizing workshops + +## Our Sponsors + + + +
+ +
+ +## 📬 Contact Us + +Interested in becoming a sponsor or have collaboration ideas? Contact us at: + +- Email: [contact@mathwithcode.tech](mailto:contact@mathwithcode.tech) +- GitHub: [github.com/xirf](https://github.com/xirf) + +--- + +*Math With Code is committed to transparency in the use of sponsor funds. Reports on fund usage will be shared periodically with sponsors. \ No newline at end of file diff --git a/docs/en/statistics/measures-concentration-dispersion.md b/docs/en/statistics/measures-concentration-dispersion.md new file mode 100644 index 0000000..eec4961 --- /dev/null +++ b/docs/en/statistics/measures-concentration-dispersion.md @@ -0,0 +1,751 @@ +# Measures of Location + +Measure of location is one of the branches of descriptive statistics, +which is used to determine the position of a series of data in a distribution. +Measure of location is divided into 3, namely quartiles, deciles, and percentiles. +Measure of location is commonly used in the case of group distributions. + +For example, in a healthcare service there are officers who measure the weight of toddlers to monitor +the development and growth of toddlers. So the location measurement is used for + +| Location size | Value | Function | +| --------------------- | ------------- | ----------------------------- | +| Percentile | 50 | Average toddler weight reference | +| Percentile | 5 | Indications of stunting in toddlers | +| Percentile | 85 | Indications of obesity in toddlers | +| Quartile | Atas | The lower limit of normal for body weight or height | +| Quartile | Bawah | Normal upper limit reference | + +## Percentile + +Percentile is the division of N data in order into 100 parts where the data is divided equally, limited by 99 percentile values. Percentile is divided into two according to the type of data, namely Single Data and Grouped Data. + +Single data is generally a series of numbers contained in a row or *array*. +The formula for calculating the percentile of single data is as follows +$$ Pi = \frac{i(n+1)}{100} $$ + +| Symbol | Explanation | +| ------------- | ------------- | +| $P_i$ | Persentil ke-i| +| i | Nilai Persentil (1 hingga 99) | +| n | Banyaknya data pada baris atau *array*| + +The following is an example case of percentiles of single data and grouped data. + +### Data Tunggal +For example, there is a row of numbers like below and we want to find the 50th percentile. + +:::tabs key:lang +== JavaScript +```javascript +// Single Data Set +const dataSet = [25, 27, 29, 18, 20, 21, 23, 10, 12, 14, 16]; + +const percentValue = 100; +const percentileValue = 50; // Percentile to calculate (1-99) +const startIndex = 1; +let percentileResult = 0; + +// Sort data in ascending order +const sortedData = dataSet.sort((a, b) => a - b); +const dataCount = dataSet.length; + +// Calculate percentile position +const position = (dataCount + startIndex) * (percentileValue / percentValue); + +// If position is an integer, take the value at that position +if (Number.isInteger(position)) { + percentileResult = sortedData[position - startIndex]; // 20 +} else { + // If position is not an integer, perform interpolation + const lowerIndex = Math.floor(position) - startIndex; + const upperIndex = Math.ceil(position) - startIndex; + + // Values at lower and upper indices + const lowerValue = sortedData[lowerIndex]; + const upperValue = sortedData[upperIndex]; + + // Interpolation to calculate the percentile value + percentileResult = lowerValue + (upperValue - lowerValue) * (position - Math.floor(position)); // 20 +} +``` + +==Python +```python +# Single Data Set +data_set = [25, 27, 29, 18, 20, 21, 23, 10, 12, 14, 16] + +percent_value = 100 +percentile_value = 50 # Percentile to calculate (1-99) +start_index = 1 +percentile_result = 0 + +# Sort data in ascending order +sorted_data = sorted(data_set) +data_count = len(data_set) + +# Calculate percentile position +position = (data_count + start_index) * (percentile_value / percent_value) + +# If position is an integer, take the value at that position +if position.is_integer(): + percentile_result = sorted_data[int(position) - start_index] # 20 +else: + # If position is not an integer, perform interpolation + lower_index = int(position) - start_index + upper_index = int(position + 1) - start_index + + # Values at lower and upper indices + lower_value = sorted_data[lower_index] + upper_value = sorted_data[upper_index] + + # Interpolation to calculate the percentile value + percentile_result = lower_value + (upper_value - lower_value) * (position - int(position)) # 20 + print(percentile_result) +``` +::: + +### Grouped Data + +The following is the percentile formula for grouped data + +$$ P_p = L + \frac{p/100 - \sum f_b}{f_i} \times c $$ + +| Symbol | Explanation | +| ------------- | --------------------------------------------------------------------- | +| $P_p$ | The i-th percentile value | +| L | The lower bound of the interval class that contains $P_p$ | +| p | Percentile values ​​(1 to 99) | +| $\sum f_b$ | The cumulative frequency sum before the interval class containing $P_p$ | +| $f_i$ | The frequency of the interval class containing $P_p$ | +| c | The length of the loading interval class $P_p$ | + +For example, there is data on the age group of citizens under 1 year to 40 years as below and we want to find the 50th percentile of this data group. +:::tabs key:lang +== JavaScript +```javascript +// Group Data +const groupData = [ + { interval: [0, 10], frequency: 5 }, + { interval: [10, 20], frequency: 10 }, + { interval: [20, 30], frequency: 8 }, + { interval: [30, 40], frequency: 2 } +]; + +const percentileValue = 50; // 1-99 +const initialValue = 0; +const percentValue = 100; +let percentileResult = 0; + +// Function to calculate total frequency +function calculateTotalFrequency(data) { + return data.reduce((total, item) => total + item.frequency, initialValue); +} + +// Function to calculate cumulative data +function calculateCumulativeData(data) { + let cumulativeFrequency = 0; + return data.map(item => { + cumulativeFrequency += item.frequency; + return { ...item, cumulative: cumulativeFrequency }; + }); +} + +// Function to calculate percentile value +function calculatePercentileValue(groupData, cumulativeData, percentile) { + const totalFrequency = calculateTotalFrequency(groupData); + const position = (percentile / percentValue) * totalFrequency; + + const intervalClass = cumulativeData.find(item => item.cumulative >= position); + + if (intervalClass) { + const [lowerBound, upperBound] = intervalClass.interval; + const cumulativeLower = cumulativeData[cumulativeData.indexOf(intervalClass) - 1]?.cumulative || 0; + const frequencyInClass = intervalClass.frequency; + + return lowerBound + ((position - cumulativeLower) / frequencyInClass) * (upperBound - lowerBound); + } + + return 0; // Or a default value if the intervalClass is not found +} + +// Calculate the 50th percentile value +percentileResult = calculatePercentileValue(groupData, calculateCumulativeData(groupData), percentileValue); // 17.5 +``` +==Python +```python +# Group Data +group_data = [ + {"interval": [0, 10], "frequency": 5}, + {"interval": [10, 20], "frequency": 10}, + {"interval": [20, 30], "frequency": 8}, + {"interval": [30, 40], "frequency": 2} +] + +percentile_value = 50 # 1-99 +initial_value = 0 +percent_value = 100 +percentile_result = 0 + +# Function to calculate total frequency +def calculate_total_frequency(data): + return sum(item['frequency'] for item in data) + +# Function to calculate cumulative data +def calculate_cumulative_data(data): + cumulative_frequency = 0 + result = [] + for item in data: + cumulative_frequency += item['frequency'] + result.append({**item, 'cumulative': cumulative_frequency}) + return result + +# Function to calculate percentile value +def calculate_percentile_value(group_data, cumulative_data, percentile): + total_frequency = calculate_total_frequency(group_data) + position = (percentile / percent_value) * total_frequency + + interval_class = next((item for item in cumulative_data if item['cumulative'] >= position), None) + + if interval_class: + lower_bound, upper_bound = interval_class['interval'] + cumulative_lower = cumulative_data[cumulative_data.index(interval_class) - 1]['cumulative'] if cumulative_data.index(interval_class) > 0 else 0 + frequency_in_class = interval_class['frequency'] + + return lower_bound + ((position - cumulative_lower) / frequency_in_class) * (upper_bound - lower_bound) + + return 0 # Or a default value if the interval_class is not found + +# Calculate the 50th percentile value +percentile_result = calculate_percentile_value(group_data, calculate_cumulative_data(group_data), percentile_value) # 17.5 +print(percentile_result) +``` + +::: + +## Decile +Decile is a division of N data in order into 10 parts where the data is divided equally, so that there are 9 decile values. Decile is divided into two according to the type of data, namely Single Data and Grouped Data. + +Single data is generally a series of numbers contained in a row or array . The formula for calculating single data deciles is as follows +$$ Di = \frac{i(n+1)}{10} $$ + +| Symbol | Explanation | +| ------------- | ------------------------------------- | +| $D_i$ | The i-th decile | +| i | Decile Values ​​(1 to 9) | +| n | The amount of data in a row or *array*| + +Here is an example *case* of single data decile and grouped data (using previous data) + +### Single Data +For example, there is a row of numbers like below and we want to find the 5th decile. + +:::tabs key:lang +== JavaScript +```javascript +// Single Data +const singleData = [25, 27, 29, 18, 20, 21, 23, 10, 12, 14, 16]; + +const percentValue = 10; +const decileValue = 5; // 1-9 +let totalDecile = 0; + +// Sorting data in ascending order +const sortedData = [...singleData].sort((a, b) => a - b); +const dataSize = singleData.length; + +// Calculating the position of the decile value +const position = (decileValue * (dataSize + 1)) / percentValue; + +if (Number.isInteger(position)) { + totalDecile = sortedData[position - 1]; // 20 +} else { + const lowerIndex = Math.floor(position) - 1; + const upperIndex = Math.ceil(position) - 1; + + const lowerValue = sortedData[lowerIndex]; + const upperValue = sortedData[upperIndex]; + + // Interpolation to calculate the decile value + totalDecile = lowerValue + (upperValue - lowerValue) * (position - Math.floor(position)); // 20 +} +``` +==Python +```python +# Single Data +single_data = [25, 27, 29, 18, 20, 21, 23, 10, 12, 14, 16] + +percent_value = 10 +decile_value = 5 # 1-9 +total_decile = 0 + +# Sorting data in ascending order +sorted_data = sorted(single_data) +data_size = len(single_data) + +# Calculating the position of the decile value +position = (decile_value * (data_size + 1)) / percent_value + +if position.is_integer(): + total_decile = sorted_data[int(position) - 1] # 20 +else: + lower_index = int(position) - 1 + upper_index = lower_index + 1 + + lower_value = sorted_data[lower_index] + upper_value = sorted_data[upper_index] + + # Interpolation to calculate the decile value + total_decile = lower_value + (upper_value - lower_value) * (position - int(position)) # 20 + +print(total_decile) +``` +::: + +### Grouped Data + +The following is the decile formula for grouped data +$$ D_i = L + \frac{i/10 - \sum f_b}{f_i} \times c $$ + +| Symbol | Explanation | +| ------------- | --------------------------------------------------------------------- | +| $D_i$ | The value of the i-th decile | +| L | The lower bound of the interval class that contain $D_i$ | +| i | Decile values ​​(1 to 9) | +| $\sum f_b$ | The cumulative frequency sum before the interval class containing $D_i$ | +| $f_i$ | The frequency of the interval class containing $D_i$ | +| c | The length of the loading interval class $D_i$ | + +For example, there is data on the age group of citizens under 1 year to 40 years as below and we want to find the 9th decile of this data group +:::tabs key:lang +== JavaScript +```javascript +// Group Data +const groupData = [ + { interval: [0, 10], frequency: 5 }, + { interval: [10, 20], frequency: 10 }, + { interval: [20, 30], frequency: 8 }, + { interval: [30, 40], frequency: 2 } +]; + +const decileValue = 9; // 1-9 for deciles 1 through 9 +const initialValue = 0; +const percentValue = 10; +let resultDecile = 0; + +// Function to calculate total frequency +function calculateTotalFrequency(data) { + return data.reduce((total, item) => total + item.frequency, initialValue); +} + +// Function to calculate cumulative data +function calculateCumulativeData(data) { + let cumulativeFrequency = 0; + return data.map(item => { + cumulativeFrequency += item.frequency; + return { ...item, cumulative: cumulativeFrequency }; + }); +} + +// Function to calculate decile value +function calculateDecileValue(groupData, cumulativeData, decile) { + const totalFrequency = calculateTotalFrequency(groupData); + const position = (decile / percentValue) * totalFrequency; + + const intervalClass = cumulativeData.find(item => item.cumulative >= position); + + if (intervalClass) { + const [lowerBound, upperBound] = intervalClass.interval; + const cumulativeLower = cumulativeData[cumulativeData.indexOf(intervalClass) - 1]?.cumulative || 0; + const frequencyInClass = intervalClass.frequency; + + return lowerBound + ((position - cumulativeLower) / frequencyInClass) * (upperBound - lowerBound); + } + + return 0; // Or a default value if no intervalClass is found +} + +// Calculating the 9th decile value +decileResult = calculateDecileValue(groupData, calculateCumulativeData(groupData), decileValue); // 29.375 +``` + +==Python +```python +# Group Data +group_data = [ + {"interval": [0, 10], "frequency": 5}, + {"interval": [10, 20], "frequency": 10}, + {"interval": [20, 30], "frequency": 8}, + {"interval": [30, 40], "frequency": 2} +] + +decile_value = 9 # 1-9 for deciles 1 through 9 +initial_value = 0 +percent_value = 10 +result_decile = 0 + +# Function to calculate total frequency +def calculate_total_frequency(data): + return sum(item["frequency"] for item in data) + +# Function to calculate cumulative data +def calculate_cumulative_data(data): + cumulative_frequency = 0 + result = [] + for item in data: + cumulative_frequency += item["frequency"] + result.append({**item, "cumulative": cumulative_frequency}) + return result + +# Function to calculate decile value +def calculate_decile_value(group_data, cumulative_data, decile): + total_frequency = calculate_total_frequency(group_data) + position = (decile / percent_value) * total_frequency + + interval_class = next((item for item in cumulative_data if item["cumulative"] >= position), None) + + if interval_class: + lower_bound, upper_bound = interval_class["interval"] + cumulative_lower = cumulative_data[cumulative_data.index(interval_class) - 1]["cumulative"] if cumulative_data.index(interval_class) > 0 else 0 + frequency_in_class = interval_class["frequency"] + + return lower_bound + ((position - cumulative_lower) / frequency_in_class) * (upper_bound - lower_bound) + + return 0 # Or a default value if no interval_class is found + +# Calculating the 9th decile value +decile_result = calculate_decile_value(group_data, calculate_cumulative_data(group_data), decile_value) # 29.375 +print(decile_result) +``` +::: + +## Quartile + +Quartiles are the division of N data in order into 4 parts where the data is divided equally, so that there are 3 quartile values. +Quartiles are divided into two according to the type of data, namely Single Data and Grouped Data. + +Single data is generally a series of numbers contained in a row or array. The formula for calculating the quartile of single data is as follows: +$$ Qi = \frac{i(n+1)}{4} $$ + +| Symbol | Explanation | +| ------------- | ------------------------------------- | +| Qi | i-th quartile | +| i | Quartile Values ​​(1 to 9) | +| n | The amount of data in a row or *array*| + +### Single Data +For example, there is a row of numbers like below and we want to find the 2nd quartile + +:::tabs key:lang +== JavaScript +```javascript +// Single Data +const singleData = [25, 27, 29, 18, 20, 21, 23, 10, 12, 14, 16]; + +const percentValue = 4; +const quartileValue = 2; // 1-3 +let resultQuartile = 0; + +// Sorting the data in ascending order +const sortedData = [...singleData].sort((a, b) => a - b); +const dataCount = singleData.length; + +// Calculating the position of the quartile value +const position = (quartileValue * (dataCount + 1)) / percentValue; + +if (Number.isInteger(position)) { + resultQuartile = sortedData[position - 1]; // 20 +} else { + const lowerIndex = Math.floor(position) - 1; + const upperIndex = Math.ceil(position) - 1; + + const lowerValue = sortedData[lowerIndex]; + const upperValue = sortedData[upperIndex]; + + // Interpolation to calculate the quartile value + resultQuartile = lowerValue + (upperValue - lowerValue) * (position - Math.floor(position)); // 20 +} +``` +== Python +``` python +# Single Data +singleData = [25, 27, 29, 18, 20, 21, 23, 10, 12, 14, 16] + +percentValue = 4 +quartileValue = 2 # 1-3 +resultQuartile = 0 + +# Sorting the data in ascending order +sortedData = sorted(singleData) +dataCount = len(singleData) + +# Calculating the position of the quartile value +position = (quartileValue * (dataCount + 1)) / percentValue + +if position.is_integer(): + resultQuartile = sortedData[int(position) - 1] # 20 +else: + lowerIndex = int(position) - 1 + upperIndex = lowerIndex + 1 + + lowerValue = sortedData[lowerIndex] + upperValue = sortedData[upperIndex] + + # Interpolation to calculate the quartile value + resultQuartile = lowerValue + (upperValue - lowerValue) * (position - int(position)) # 20 + +print(resultQuartile) +``` +::: + +### Grouped Data + +The following is the quartile formula for grouped data + +$$ Q_i = L + \frac{i/4 - \sum f_b}{f_i} \times c $$ + +| Simbol | Pengertian | +| ------------- | --------------------------------------------------------------------- | +| $Q_i$ | The value of the i-th decile | +| L | The lower bound of the interval class that contains $Q_i$ | +| i | Decile values ​​(1 to 9) | +| $\sum f_b$ | The cumulative frequency sum before the interval class containing $Q_i$ | +| $f_i$ | The frequency of the interval class containing $Q_i$ | +| c | The length of the loading interval class $Q_i$ | + +For example, there is data on the age group of citizens under 1 year to 40 years as below and we want to find the 2nd quartile of this data group +:::tabs key:lang +== JavaScript +```javascript +// Group Data +const groupData = [ + { interval: [0, 10], frequency: 5 }, + { interval: [10, 20], frequency: 10 }, + { interval: [20, 30], frequency: 8 }, + { interval: [30, 40], frequency: 2 } +]; + +const percentValue = 4; +const quartileValue = 2; // 1-3 +const initialValue = 0; +let resultQuartile = 0; + +// Function to calculate total frequency +function calculateTotalFrequency(data) { + return data.reduce((sum, item) => sum + item.frequency, initialValue); +} + +// Function to calculate cumulative data +function calculateCumulativeData(data) { + let cumulativeFrequency = 0; + return data.map(item => { + cumulativeFrequency += item.frequency; + return { ...item, cumulative: cumulativeFrequency }; + }); +} + +// Function to calculate quartile value +function calculateQuartileValue(groupData, cumulativeData, quartile) { + const totalFrequency = calculateTotalFrequency(groupData); + const position = (quartile / percentValue) * totalFrequency; + + const intervalClass = cumulativeData.find(item => item.cumulative >= position); + + if (intervalClass) { + const [lowerLimit, upperLimit] = intervalClass.interval; + const cumulativeLower = cumulativeData[cumulativeData.indexOf(intervalClass) - 1]?.cumulative || 0; + const frequencyInClass = intervalClass.frequency; + + return lowerLimit + ((position - cumulativeLower) / frequencyInClass) * (upperLimit - lowerLimit); + } + + return 0; // Or a default value if the interval class is not found +} + +// Calculate the 2nd quartile value +quartileResult = calculateQuartileValue(groupData, calculateCumulativeData(groupData), quartileValue); // 17.5 +``` +== Kotlin +```kotlin +// Group Data +data class GroupData(val interval: Pair, val frequency: Int) + +val groupData = listOf( + GroupData(0 to 10, 5), + GroupData(10 to 20, 10), + GroupData(20 to 30, 8), + GroupData(30 to 40, 2) +) + +val percentValue = 4 +val quartileValue = 2 // 1-3 +val initialValue = 0 +var resultQuartile = 0.0 + +// Function to calculate total frequency +fun calculateTotalFrequency(data: List): Int { + return data.sumOf { it.frequency } +} + +// Function to calculate cumulative data +fun calculateCumulativeData(data: List): List { + var cumulativeFrequency = 0 + return data.map { + cumulativeFrequency += it.frequency + it.copy(frequency = cumulativeFrequency) + } +} + +// Function to calculate quartile value +fun calculateQuartileValue(groupData: List, cumulativeData: List, quartile: Int): Double { + val totalFrequency = calculateTotalFrequency(groupData) + val position = (quartile.toDouble() / percentValue) * totalFrequency + + val intervalClass = cumulativeData.find { it.frequency >= position } + + intervalClass?.let { + val (lowerLimit, upperLimit) = it.interval + val cumulativeLower = cumulativeData.getOrNull(cumulativeData.indexOf(it) - 1)?.frequency ?: 0 + val frequencyInClass = it.frequency - cumulativeLower + + return lowerLimit + ((position - cumulativeLower) / frequencyInClass) * (upperLimit - lowerLimit) + } + + return 0.0 // Or a default value if the interval class is not found +} + +// Calculate the 2nd quartile value +resultQuartile = calculateQuartileValue(groupData, calculateCumulativeData(groupData), quartileValue) +println(resultQuartile) // Output: 29.375 +``` +== C++ +```cpp +#include +#include +#include // for std::accumulate + +// Structure to represent group data +struct GroupData { + std::pair interval; // Interval for the group + int frequency; // Frequency count for the group +}; + +int decileValue = 9; // 1-9 for the 1st to 9th decile +int initialValue = 0; // Initial value for calculations +int percentValue = 10; // Percentage value +double resultDecile = 0; // Variable to store the result for the decile + +// Function to calculate total frequency +int calculateTotalFrequency(const std::vector& data) { + return std::accumulate(data.begin(), data.end(), initialValue, + [](int sum, const GroupData& item) { + return sum + item.frequency; // Summing up the frequencies + }); +} + +// Function to calculate cumulative data +std::vector calculateCumulativeData(const std::vector& data) { + int cumulativeFrequency = 0; // Variable to hold cumulative frequency + std::vector cumulativeData; // Vector to store cumulative data + + for (const auto& item : data) { + cumulativeFrequency += item.frequency; // Update cumulative frequency + cumulativeData.push_back({ item.interval, cumulativeFrequency }); // Add to cumulative data + } + + return cumulativeData; // Return the cumulative data +} + +// Function to calculate decile value +double calculateDecileValue(const std::vector& groupData, const std::vector& cumulativeData, int decile) { + int totalFrequency = calculateTotalFrequency(groupData); // Get total frequency + double position = (static_cast(decile) / percentValue) * totalFrequency; // Calculate position for the decile + + // Find the interval class where the cumulative frequency is greater than or equal to position + auto intervalClass = std::find_if(cumulativeData.begin(), cumulativeData.end(), + [position](const GroupData& item) { + return item.frequency >= position; // Condition for finding the interval + }); + + if (intervalClass != cumulativeData.end()) { // If the interval class is found + int lowerLimit = intervalClass->interval.first; // Lower limit of the interval + int upperLimit = intervalClass->interval.second; // Upper limit of the interval + int index = std::distance(cumulativeData.begin(), intervalClass); // Index of the found interval + int cumulativeLower = (index > 0) ? cumulativeData[index - 1].frequency : 0; // Cumulative frequency below the found class + int frequencyInClass = intervalClass->frequency - cumulativeLower; // Frequency within the class + + // Interpolating to find the decile value + return lowerLimit + ((position - cumulativeLower) / frequencyInClass) * (upperLimit - lowerLimit); + } + + return 0.0; // Return 0 if the interval class is not found (or a default value) +} + +int main() { + // Group data with intervals and frequencies + std::vector groupData = { + {{0, 10}, 5}, + {{10, 20}, 10}, + {{20, 30}, 8}, + {{30, 40}, 2} + }; + + // Calculate the value of the 9th decile + resultDecile = calculateDecileValue(groupData, calculateCumulativeData(groupData), decileValue); + std::cout << resultDecile << std::endl; // Output: 29.375 + + return 0; +} + +``` +==Python +```python +# Group data +dataGroups = [ + {"interval": [0, 10], "frequency": 5}, + {"interval": [10, 20], "frequency": 10}, + {"interval": [20, 30], "frequency": 8}, + {"interval": [30, 40], "frequency": 2} +] + +percentageCount = 4 +quartileValue = 2 # 1-3 for quartiles +initialValue = 0 +resultQuartile = 0 + +# Function to calculate total frequency +def calculateTotalFrequency(data): + return sum(item["frequency"] for item in data) + +# Function to calculate cumulative data +def calculateCumulativeData(data): + cumulativeFrequency = 0 + results = [] + for item in data: + cumulativeFrequency += item["frequency"] + results.append({**item, "cumulative": cumulativeFrequency}) # Add cumulative frequency to results + return results + +# Function to calculate quartile value +def calculateQuartileValue(dataGroups, cumulativeData, quartile): + totalFrequency = calculateTotalFrequency(dataGroups) # Calculate total frequency + position = (quartile / percentageCount) * totalFrequency # Calculate position for the quartile + + # Find the class interval where cumulative frequency is greater than or equal to position + classInterval = next((item for item in cumulativeData if item["cumulative"] >= position), None) + + if classInterval: # If the class interval is found + lowerBound, upperBound = classInterval["interval"] # Get bounds of the interval + cumulativeLower = cumulativeData[cumulativeData.index(classInterval) - 1]["cumulative"] if cumulativeData.index(classInterval) > 0 else 0 + frequencyInClass = classInterval["frequency"] # Frequency in the class + + # Interpolate to find the quartile value + return lowerBound + ((position - cumulativeLower) / frequencyInClass) * (upperBound - lowerBound) + + return 0 # Return 0 or a default value if the class interval is not found + +# Calculate the value of the 2nd quartile +resultQuartile = calculateQuartileValue(dataGroups, calculateCumulativeData(dataGroups), quartileValue) # 17.5 +print(resultQuartile) +``` +::: diff --git a/docs/en/statistics/simple-linear-regression.md b/docs/en/statistics/simple-linear-regression.md new file mode 100644 index 0000000..ffa7fcb --- /dev/null +++ b/docs/en/statistics/simple-linear-regression.md @@ -0,0 +1,366 @@ +--- +contributors: + - name: "Fadjar" + username: "fadjarrafi" +--- + +# Simple Linear Regression + +Have you ever wondered how large companies make their advertising investment decisions? Or how real estate determines house selling prices? The answer lies in a statistical technique called simple linear regression. +Simple linear regression is a statistical method that allows us to understand and predict the relationship between two variables. Think of it as finding a "connecting thread" that links advertising costs ($x$) with sales levels ($y$). + +Mathematically, this relationship can be expressed with the formula: + +$$ +y = \beta_0 + \beta_1 x + \varepsilon +$$ + +Where: + +| Symbol | Meaning | +| ------------- | ------------- | +| $x$ | Independent Variable | +| $y$ | Dependent Variable | +| β₀ | *Intercept* (value of $y$ when $x$ = 0)| +| β₁ | *Slope* (how much $y$ changes for each unit change in $x$)| +| ε | *Error term*| + +## Functions of Linear Regression + +Linear regression has two crucial roles in data analysis: + +1. Relationship Verification + + - Statistically prove whether there is a real relationship between two variables + - Measure how strong that relationship is + - Example: Is it true that education level affects income level? + + +2. Predictive Power + + - Enables us to predict future values + - Make business decisions based on historical data + - Example: If we increase the advertising budget by $x$, what sales increase ($y$) can we expect? + +## Calculating Linear Regression + +Let's take a case where we want to know the correlation between advertising costs ($x$) and sales ($y$). For example, we have data as follows: + +| Advertising Cost | Units | +| ------------ | ------------- | +| 100 | 500 | +| 200 | 700 | +| 300 | 900 | +| 400 | 1100 | +| 500 | 1300 | + +Before we calculate simple linear regression with this data, we need to: + +1. Calculate the Slope $\beta_1$ +2. Calculate the Intercept $\beta_0$ + +### Calculating the Slope ($\beta_1$) + +The slope represents the change in variable $y$ for each change in variable $x$. We can calculate the slope using the following formula: + +$$ +\beta_1 = \frac{\sum(x_i - \bar{x})(y_i - \bar{y})}{\sum(x_i - \bar{x})^2} +$$ + +Where: + +| Symbol | Meaning | +| ----------------- | ------------- | +| $x_i$ | Individual values of the Independent variable | +| $y_i$ | Individual values of the Dependent variable | +| $\bar{x}$ | Mean of all Independent variable values | +| $\bar{y}$ | Mean of all Dependent variable values | + +Let's first calculate the mean of each advertising cost ($x$) and sales units ($y$): + +$$ \bar{x} = (100 + 200 + 300 + 400 + 500) / 5 = 300 $$ +$$ \bar{y} = (500 + 700 + 900 + 1100 + 1300) / 5 = 900 $$ + +After we find the means of advertising costs and sales units, next we calculate the Slope: + +$$ (100 - 300)(500 - 900) = (-200)(-400) = 80,000 $$ +$$ (200 - 300)(700 - 900) = (-100)(-200) = 20,000 $$ +$$ (300 - 300)(900 - 900) = (0)(0) = 0 $$ +$$ (400 - 300)(1100 - 900) = (100)(200) = 20,000 $$ +$$ (500 - 300)(1300 - 900) = (200)(400) = 80,000 $$ + +$$ Total = 200,000 $$ + +$$ (100 - 300)² = (-200)² = 40,000 $$ +$$ (200 - 300)² = (-100)² = 10,000 $$ +$$ (300 - 300)² = (0)² = 0 $$ +$$ (400 - 300)² = (100)² = 10,000 $$ +$$ (500 - 300)² = (200)² = 40,000 $$ + +$$ Total = 100,000 $$ +$$ \beta_1 = 200,000/100,000 = 2 $$ + +From the sales data above, we get a Slope value = 2, which means that for every 1 unit increase in cost ($x$), sales ($y$) will increase by 2 units. + +### Calculating the Intercept ($\beta_0$) + +After we find the Slope value, we calculate the Intercept value with the following formula: + +$$ +\beta_0 = \bar{y} - \beta_1\bar{x} +$$ + +Where: + +| Symbol | Meaning | +| ----------------- | ------------- | +| $\bar{y}$ | Mean of all independent variable values | +| $\bar{x}$ | Mean of all dependent variable values | +| $\beta_1$ | *Slope* | + +Let's calculate the Intercept from the Slope we calculated earlier: + +$$ \beta_0 = 900 - (2 × 300) $$ +$$ \beta_0 = 300 $$ + +This means when advertising costs are 0, the predicted sales are 300 units. After we know the Slope and Intercept, we can input them into the linear regression equation as follows: + +$$ y = 300 + 2x $$ + +So how do we use this formula to make predictions? For example, in the next advertisement, we want to know how many sales we'll get if we spend 250 on advertising. We input the advertising cost of 250 into the equation we've determined: + +$$ y = 300 + 2(250) $$ +$$ y = 300 + 500 $$ +$$ y = 800 $$ + +So if we spend 250 on advertising, we can predict sales of 800 units. Here's the equation we've obtained if we draw it in a graph: + + + +The linear regression calculation we've made can be simulated in the following program: + +:::tabs +== JavaScript +```js +// Sales and advertising data +const sales_data = { + advertising_cost: [100, 200, 300, 400, 500], + units_sold: [500, 700, 900, 1100, 1300] +}; + +// Calculate average of array +function calculate_mean(data) { + return data.reduce((total, value) => total + value, 0) / data.length; +} + +// Calculate slope (β₁) from data +function calculate_slope(data) { + const mean_x = calculate_mean(data.advertising_cost); + const mean_y = calculate_mean(data.units_sold); + + let numerator = 0; + let denominator = 0; + + // Calculate numerator and denominator for slope formula + for (let i = 0; i < data.advertising_cost.length; i++) { + const diff_x = data.advertising_cost[i] - mean_x; + const diff_y = data.units_sold[i] - mean_y; + + numerator += diff_x * diff_y; + denominator += diff_x * diff_x; + } + + return numerator / denominator; +} + +// Calculate intercept (β₀) from data +function calculate_intercept(data, slope) { + const mean_x = calculate_mean(data.advertising_cost); + const mean_y = calculate_mean(data.units_sold); + + return mean_y - (slope * mean_x); +} + +// Predict units sold based on advertising cost +function predict_sales(advertising_cost, slope, intercept) { + return intercept + (slope * advertising_cost); +} + +// Calculate regression +const slope = calculate_slope(sales_data); +const intercept = calculate_intercept(sales_data, slope); + +// Display results +console.log(`Slope (β₁): ${slope}`); // output: 2 +console.log(`Intercept (β₀): ${intercept}`); // output: 300 + +// Example prediction +const new_cost = 250; +const prediction = predict_sales(new_cost, slope, intercept); +console.log(`${prediction} units`); +``` +::: +## Classical Assumptions of Linear Regression + +Before starting to apply linear regression, it's important for us to understand its basic assumptions: + +1. Linearity + +The first and most fundamental assumption is that the relationship between the independent variable ($x$) and dependent variable ($y$) must be linear. Imagine if we plot the data points on a graph, these points should form a pattern that can be approximated by a straight line. We can check this assumption by creating a scatter plot of our data. If the pattern formed is far from linear, for example forming a curve or other pattern, then we need to perform data transformation first. Common transformations include logarithms, square roots, or other transformations that suit the data shape. + +2. Independence + +The second assumption is that each observation in our data must be independent or not influence each other. This is particularly important when working with data collected over time (time series). For example, if we're analyzing daily sales, today's sales should not be influenced by yesterday's sales. If there is influence between observations (autocorrelation), our analysis results could be biased. We can check this assumption with an ACF (Autocorrelation Function) plot or using statistical tests like Durbin-Watson. + +3. Homoscedasticity + +This term, which might sound complicated, actually refers to a fairly simple concept: the variance of errors (residuals) must be constant for all values of the independent variable. In the context of our example about advertising and sales, this means the level of prediction error should be relatively the same, both for low and high advertising costs. We can check this assumption by plotting residuals against predicted values. If the plot shows a particular pattern (like a funnel shape), then this assumption is not met and we need to perform data transformation or use more robust analysis methods. + +4. Normality + +The final assumption is that the residuals or errors must follow a normal distribution. This is important especially when we want to perform hypothesis testing or create confidence intervals. Imagine if we make a histogram of the errors, its shape should resemble a symmetrical bell (normal curve). We can check this assumption in several ways, from simple ones like making residual histograms or Q-Q plots, to formal tests like Shapiro-Wilk or Kolmogorov-Smirnov. + + +## Testing the Equation with Coefficient of Determination ($R^2$) + +Then how do we know the ability of the regression equation to explain how much the independent variables together (simultaneously) affect the dependent variable? This is where we perform the Coefficient of Determination Test. The coefficient of determination is a measure that shows how well the regression model explains the data. We can calculate the coefficient of determination with the formula: + +$$ R^2 = 1 - \frac{\sum(y_i - \hat{y_i})^2}{\sum(y_i - \bar{y})^2} $$ + +Where: + +| Symbol | Meaning | +| ----------------- | ------------- | +| $y_i$ | Actual Value | +| $\hat{y_i}$ | Predicted Value | +| $\bar{y}$ | Mean of Actual Values | + +The coefficient of determination describes the amount of variance (information) in variable $y$ that can be provided by our regression model. The coefficient value ranges from 0 to 1. If the $R^2$ value is multiplied by 100%, this shows the percentage of variance (information) in variable $y$. + +To calculate $R^2$, we need to calculate: + +1. Predicted Values ($\hat{y_i}$) for Each $x$ +2. Mean of Actual $y$ Values ($\bar{y}$) +3. SS_total and SS_residual Values + +### Calculating Predicted Values ($\hat{y_i}$) for Each $x$ + +We calculate each value we have with the linear regression equation we obtained earlier, which is: $y = 300 + 2x$ + +| Advertising Cost ($x$) | Units ($y$) | $\hat{y}$ (Y Predicted) | +| ---------------- | ------------- | ---------------------- | +| 100 | 500 | 300 + 2(100) = 500 | +| 200 | 700 | 300 + 2(200) = 700 | +| 300 | 900 | 300 + 2(300) = 900 | +| 400 | 1100 | 300 + 2(400) = 1100 | +| 500 | 1300 | 300 + 2(500) = 1300 | + +### Calculating Mean of Actual $y$ Values ($\bar{y}$) + +$$ \bar{y} = (500 + 700 + 900 + 1100 + 1300) / 5 = 900 $$ + +$$ (500 - 900)² = (-400)² = 160,000 $$ +$$ (700 - 900)² = (-200)² = 40,000 $$ +$$ (900 - 900)² = 0 $$ +$$ (1100 - 900)² = (200)² = 40,000 $$ +$$ (1300 - 900)² = (400)² = 160,000 $$ +$$ SStotal = 400,000 $$ + +### Calculating $R^2$ + +We can calculate $R^2$ using the formula: + +$$ R^2 = 1 - (SSresidual / SStotal) $$ + +Where: + +| Symbol | Meaning | +| ----------------- | ------------- | +| $SSresidual$ | sum of squares due to regression | +| $SStotal$ | total sum of squares | + +let's calculate total $SStotal$ and $SSresidual$ as follows: +$$ SStotal = \sum(y - \bar{y})^2 $$ + +$$ (500 - 500)² = 0 $$ +$$ (700 - 700)² = 0 $$ +$$ (900 - 900)² = 0 $$ +$$ (1100 - 1100)² = 0 $$ +$$ (1300 - 1300)² = 0 $$ + +$$ SSresidual = 0 $$ + +After we get the values of $SStotal$ and $SSresidual$, we input them into the coefficient of determination formula: + +$$ R^2 = 1 - (0 / 400,000) $$ +$$ R^2 = 1 $$ + +The result $R^2$ = 1 shows that: + +1. The model explains 100% of the variation in the data +2. All data points lie exactly on the regression line +3. The model's predictions are perfect for the existing data + +Here's the $R^2$ calculation if we depict it through a graph: + + + + + + + + + + + + + + + + + Advertising Cost (X) + Sales (Y) + + + + + + + + + + + + + R² = 1.0 + Perfect Fit + + +This shows that even with little variation in the data, $R^2$ can still be very high if the model fits the data pattern. We can simulate the coefficient of determination calculation with the following program: + +:::tabs +== JavaScript +```js +// Calculate coefficient of determination (R²) +function calculate_r_squared(data, slope, intercept) { + const mean_y = calculate_mean(data.units_sold); + + let ss_total = 0; // Sum of squares total + let ss_residual = 0; // Sum of squares residual + + for (let i = 0; i < data.advertising_cost.length; i++) { + const y_predicted = intercept + (slope * data.advertising_cost[i]); + const y_actual = data.units_sold[i]; + + ss_total += Math.pow(y_actual - mean_y, 2); + ss_residual += Math.pow(y_actual - y_predicted, 2); + } + + return 1 - (ss_residual / ss_total); +} + +// Usage +const r_squared = calculate_r_squared(sales_data, slope, intercept); +console.log(`R² (Coefficient of Determination): ${r_squared.toFixed(4)}`); // Output: 0.9989 which we round to 1 +``` +::: diff --git a/docs/algebra/function.md b/docs/id/algebra/function.md similarity index 87% rename from docs/algebra/function.md rename to docs/id/algebra/function.md index 0e7eaf7..4b6fd4b 100644 --- a/docs/algebra/function.md +++ b/docs/id/algebra/function.md @@ -9,7 +9,7 @@ Dalam matematika fungsi aljabar merupakan suatu notasi yang menghubungkan dua hi Fungsi aljabar memiliki konsep yang mirip dengan fungsi yang ada di pemrograman dimana keduanya memiliki *input* dan *output*. Misalnya fungsi $f(x) = 2x + 3$ apabila kita jadikan sebagai fungsi di pemrograman, maka akan menjadi seperti berikut: -:::tabs +:::tabs key:lang == Javascript ``` js function fungsi(x) { @@ -33,6 +33,12 @@ fun fungsi(x: Int): Int { def fungsi(x): return 2 * x + 3 ``` +== Rust +```rust +fn fungsi(x: u64) -> u64 { + 2 * x + 3 +} +``` ::: ## Domain, Kodomain, dan Range @@ -40,7 +46,7 @@ def fungsi(x): **Kodomain** sendiri adalah himpunan semua nilai output yang mungkin dalam fungsi. Sedangkan **range** adalah himpunan semua nilai output yang benar-benar dihasilkan oleh fungsi. -Dalam pemrograman, **domain** dan **kodomain** bisa diartikan sebagai tipe data input dan output dari fungsi yang didefinisikan. +Dalam pemrograman, **domain** dan **kodomain** bisa diartikan sebagai tipe data input dan output dari fungsi yang didefinisikan. Dengan kata lain, domain dalam konteks pemrograman adalah jenis data yang bisa diterima oleh fungsi sebagai input (*parameter*), dan kodomain adalah jenis data yang dihasilkan oleh fungsi sebagai output. @@ -67,7 +73,7 @@ Fungsi logaritma adalah fungsi yang merupakan kebalikan dari fungsi eksponensial ### Fungsi Trigonometri -Fungsi trigonometri adalah fungsi yang melibatkan fungsi trigonometri seperti sin, cos, tan, dan sebagainya. Fungsi ini memiliki grafik berbentuk gelombang. Dibawah ini adalah contoh grafik fungsi trigonometri dimana +Fungsi trigonometri adalah fungsi yang melibatkan fungsi trigonometri seperti sin, cos, tan, dan sebagainya. Fungsi ini memiliki grafik berbentuk gelombang. Dibawah ini adalah contoh grafik fungsi trigonometri dimana - Merah adalah fungsi sin(x) - Hijau adalah fungsi cos(x) - Ungu adalah fungsi tan(x) @@ -76,7 +82,7 @@ Fungsi trigonometri adalah fungsi yang melibatkan fungsi trigonometri seperti si ## Operasi pada Fungsi ### Penjumlahan dan Pengurangan Fungsi -Penjumlahan dan pengurangan fungsi dilakukan dengan cara menambahkan atau mengurangkan fungsi satu dengan fungsi lainnya. Misalnya +Penjumlahan dan pengurangan fungsi dilakukan dengan cara menambahkan atau mengurangkan fungsi satu dengan fungsi lainnya. Misalnya $$f(x) = 2x + 3$$ $$g(x) = 3x - 2$$ @@ -89,7 +95,7 @@ $$\begin{align*} \end{align*}$$ Apabila kita jadikan sebagai fungsi di pemrograman, maka akan menjadi seperti berikut: -:::tabs +:::tabs key:lang == Javascript ``` js function f(x) { @@ -136,7 +142,20 @@ def g(x): def fg(x): return f(x) + g(x) +``` +== Rust +```rust +fn f(x: u64) -> u64 { + 2 * x + 3 +} +fn g(x: u64) -> u64 { + 3 * x - 2 +} + +fn fg(x: u64) -> u64 { + f(x) + g(x) +} ``` ::: @@ -155,7 +174,7 @@ $$\begin{align*} Apabila kita jadikan sebagai fungsi di pemrograman, maka akan menjadi seperti berikut: -:::tabs +:::tabs key:lang == Javascript ``` js function f(x) { @@ -203,6 +222,20 @@ def g(x): def fg(x): return f(x) * g(x) ``` +== Rust +```rust +fn f(x: u64) -> u64 { + 2 * x + 3 +} + +fn g(x: u64) -> u64 { + 3 * x - 2 +} + +fn fg(x: u64) -> u64 { + f(x) * g(x) +} +``` ::: ### Fungsi Komposisi @@ -222,7 +255,7 @@ $$\begin{align*} \end{align*}$$ Apabila kita jadikan sebagai fungsi di pemrograman, maka akan menjadi seperti berikut: -:::tabs +:::tabs key:lang == Javascript ``` js function f(x) { @@ -270,6 +303,20 @@ def g(x): def fog(x): return f(g(x)) ``` +== Rust +```rust +fn f(x: u64) -> u64 { + 2 * x + 3 +} + +fn g(x: u64) -> u64 { + 3 * x - 2 +} + +fn fog(x: u64) -> u64 { + f(g(x)) +} +``` ::: > [!NOTE] Sifat dari fungsi komposisi @@ -303,10 +350,10 @@ $$\begin{align*} Maka invers dari fungsi $f(x) = 2x + 6$ adalah $f^{-1}(x) = \frac{1}{2}x-3$ Apabila kita jadikan sebagai fungsi di pemrograman dimana nilai $x$ sudah diketahui dan outputnya adalah nilai $y$, maka akan menjadi seperti berikut: -:::tabs +:::tabs key:lang == Javascript ``` js -function inverseFunction(y, a, b) { +function inverse_function(y, a, b) { if (a === 0) { throw new Error("Nilai a tidak boleh 0"); } @@ -316,13 +363,14 @@ function inverseFunction(y, a, b) { const a = 2; // Misalkan a = 2 const b = 3; // Misalkan b = 3 const y = 7; // Nilai y (f(x)) + // f(x) = 2x + 3 -const x = inverseFunction(y, a, b); +const x = inverse_function(y, a, b); console.log(`Invers dari f(${y}) adalah x = ${x}`); ``` == C++ ``` cpp -int inverseFunction(int y, int a, int b) { +int inverse_function(int y, int a, int b) { if (a == 0) { throw "Nilai a tidak boleh 0"; } @@ -333,15 +381,16 @@ int main() { int a = 2; // Misalkan a = 2 int b = 3; // Misalkan b = 3 int y = 7; // Nilai y (f(x)) + // f(x) = 2x + 3 - int x = inverseFunction(y, a, b); + int x = inverse_function(y, a, b); cout << "Invers dari f(" << y << ") adalah x = " << x << endl; return 0; } ``` == Kotlin ``` kotlin -fun inverseFunction(y: Int, a: Int, b: Int): Int { +fun inverse_function(y: Int, a: Int, b: Int): Int { if (a == 0) { throw IllegalArgumentException("Nilai a tidak boleh 0") } @@ -352,14 +401,15 @@ fun main() { val a = 2 // Misalkan a = 2 val b = 3 // Misalkan b = 3 val y = 7 // Nilai y (f(x)) + // f(x) = 2x + 3 - val x = inverseFunction(y, a, b) + val x = inverse_function(y, a, b) println("Invers dari f($y) adalah x = $x") } ``` == Python ``` python -def inverseFunction(y, a, b): +def inverse_function(y, a, b): if a == 0: raise Exception("Nilai a tidak boleh 0") return (y - b) / a @@ -367,8 +417,27 @@ def inverseFunction(y, a, b): a = 2 # Misalkan a = 2 b = 3 # Misalkan b = 3 y = 7 # Nilai y (f(x)) + # f(x) = 2x + 3 -x = inverseFunction(y, a, b) +x = inverse_function(y, a, b) print(f"Invers dari f({y}) adalah x = {x}") ``` -::: \ No newline at end of file +== Rust +```rust +fn inverse_function(y: u64, a: u64, b: u64) -> Result { + if a == 0: + return Err("Nilai a tidak boleh 0") + Ok((y - b) / a) +} + +fn main() { + let a = 2; // Misalkan a = 2 + let b = 3; // Misalkan b = 3 + let y = 7; // Nilai y (f(x)) + + // f(x) = 2x + 3 + let x = inverse_function(y, a, b).unwrap(); + println!("Invers dari f({}) adalah x = {}", y, x); +} +``` +::: diff --git a/docs/id/algebra/graph.md b/docs/id/algebra/graph.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/algebra/linear-equation.md b/docs/id/algebra/linear-equation.md similarity index 75% rename from docs/algebra/linear-equation.md rename to docs/id/algebra/linear-equation.md index b12edae..ac9ed09 100644 --- a/docs/algebra/linear-equation.md +++ b/docs/id/algebra/linear-equation.md @@ -40,19 +40,18 @@ $$\begin{align*} 3. Sehingga nilai $x$ yang memenuhi persamaan tersebut adalah $x = 2$. Jika diimplementasikan dalam kode, maka hasilnya adalah seperti ini: -:::tabs -==javascript - +:::tabs key:lang +== Javascript ```js -function linearEquation(a, b, c) { +function linear_equation(a, b, c) { // Persamaan: a * x + b = c const x = (c - b) / a; return x; } -console.log(linearEquation(2, 3, 7)); // Output: 2 +let x = linear_equation(2, 3, 7); +console.log(`Nilai x adalah {x}`); // Output: 2 ``` - -==kotlin +== Kotlin ```kotlin val a = 2 @@ -63,11 +62,10 @@ val c = 7 val x = (c - b) / a println("Nilai x adalah: $x") ``` - == C++ ```cpp -int linearEquation(int a, int b, int c) { +int linear_equation(int a, int b, int c) { // Persamaan: a * x + b = c int x = (c - b) / a; return x; @@ -77,24 +75,39 @@ int main() { int a = 2; int b = 3; int c = 7; - int x = linearEquation(a, b, c); + + int x = linear_equation(a, b, c); cout << "Nilai x adalah: " << x << endl; return 0; } ``` - -==Python +== Python ```python -def linearEquation(a, b, c): +def linear_equation(a, b, c): # Persamaan: a * x + b = c x = (c - b) / a return x a, b, c, = 2, 3, 7 -x = linearEquation(a, b, c) +x = linear_equation(a, b, c) print(f"Nilai x adalah: {x}") ``` +== Rust +```rust +fn linear_equation(a: u64, b: u64, c: u64) -> u64 { + // Persamaan: a * x + b = c + (c - b) / a +} +fn main() { + let a = 2; + let b = 3; + let c = 7; + + let x = linear_equation(a, b, c); + println!("Nilai x adalah: {}", x); +} +``` ::: ## Persamaan Linear Dua Variabel @@ -122,7 +135,7 @@ x &= \frac{7}{2} - \frac{3y}{2} \\ 4. Nah kita dapat solusi parametrik dari $x$ -Nila parametrik inilah yang nantinya berapapun nilai $y$ yang kita masukkan akan menghasilkan nilai $x$ yang sesuai. Misalnya nilai $y = 1$ maka: +Nilai parametrik inilah yang nantinya berapapun nilai $y$ yang kita masukkan akan menghasilkan nilai $x$ yang sesuai. Misalnya nilai $y = 1$ maka: $$\begin{align*} @@ -132,7 +145,7 @@ x &= 2 \end{align*}$$ Bagaimana jika permasalahan ini kita jadikan kode? Berikut contoh implementasinya: -:::tabs +:::tabs key:lang ==javascript ```js @@ -177,13 +190,25 @@ int main() { ``` == Python ``` python -def pldv(a, b, c, y): +def pldv(a, b, c, y): x = (c - b * y) / a - return x, y + return x, y # 2x + 3y = 7 dimana y = 1 print(pldv(2, 3, 7, 1))# Output: (x: 2.0, y: 1) ``` +== Rust +```rust +fn pldv(a: u64, b: u64, c: u64, y: u64) -> (u64, u64) { + let x = (c - b * y) / a; + (x, y) +} + +fn main() { + let hasil: (u64, u64) = pldv(2, 3, 7, 1); + println!("{:?}", hasil); // Output: (2, 1) +} +``` ::: ### Metode Eliminasi @@ -225,20 +250,20 @@ Jika sudah memiliki dua persamaan kita bisa menghilangkan salah satu variabel de 6. Sehingga nilai $x$ dan $y$ yang memenuhi persamaan tersebut adalah $x = 2$ dan $y = 1$. Bagaimana jika permasalahan ini kita jadikan kode? Berikut contoh implementasinya: -:::tabs -==javascript +:::tabs key:lang +== Javascript ```js -function pldvEliminasi(a1, b1, c1, a2, b2, c2) { +function eliminasi_pldv(a1, b1, c1, a2, b2, c2) { // Menghitung koefisien untuk eliminasi let factor = a2 / a1; // Membuat persamaan baru dengan mengurangi - let newB2 = b2 - factor * b1; - let newC2 = c2 - factor * c1; + let new_b2 = b2 - factor * b1; + let new_c2 = c2 - factor * c1; // Menyelesaikan untuk y - let y = newC2 / newB2; + let y = new_c2 / new_b2; // Menghitung x dengan substitusi y ke dalam persamaan 1 let x = (c1 - b1 * y) / a1; @@ -247,21 +272,21 @@ function pldvEliminasi(a1, b1, c1, a2, b2, c2) { } // 2x - 3y = 7 dan 3x - 2y = 8 -console.log(pldvEliminasi(2, 3, 7, 3, -2, 8)); // Output: { x: 2, y: 1 } +console.log(eliminasi_pldv(2, 3, 7, 3, -2, 8)); // Output: { x: 2, y: 1 } ``` -== kotlin +== Kotlin ```kotlin -fun pldvEliminasi(a1: Int, b1: Int, c1: Int, a2: Int, b2: Int, c2: Int): Pair { +fun eliminasi_pldv(a1: Int, b1: Int, c1: Int, a2: Int, b2: Int, c2: Int): Pair { // Menghitung koefisien untuk eliminasi val factor = a2 / a1 // Membuat persamaan baru dengan mengurangi - val newB2 = b2 - factor * b1 - val newC2 = c2 - factor * c1 + val new_b2 = b2 - factor * b1 + val new_c2 = c2 - factor * c1 // Menyelesaikan untuk y - val y = newC2 / newB2 + val y = new_c2 / new_b2 // Menghitung x dengan substitusi y ke dalam persamaan 1 val x = (c1 - b1 * y) / a1 @@ -270,24 +295,23 @@ fun pldvEliminasi(a1: Int, b1: Int, c1: Int, a2: Int, b2: Int, c2: Int): Pair #include -pair pldvEliminasi(double a1, double b1, double c1, double a2, double b2, double c2) { +pair eliminasi_pldv(double a1, double b1, double c1, double a2, double b2, double c2) { // Menghitung koefisien untuk eliminasi double factor = a2 / a1; // Membuat persamaan baru dengan mengurangi - double newB2 = b2 - factor * b1; - double newC2 = c2 - factor * c1; + double new_b2 = b2 - factor * b1; + double new_c2 = c2 - factor * c1; // Menyelesaikan untuk y - double y = newC2 / newB2; + double y = new_c2 / new_b2; // Menghitung x dengan substitusi y ke dalam persamaan 1 double x = (c1 - b1 * y) / a1; @@ -296,26 +320,25 @@ pair pldvEliminasi(double a1, double b1, double c1, double a2, d } int main() { - auto result = pldvEliminasi(2, 3, 7, 4, -5, 10); - cout << "x: " << result.first << ", y: " << result.second << endl; + auto result = eliminasi_pldv(2, 3, 7, 4, -5, 10); + cout << "x: " << result.first << ", y: " << result.second << endl; // Output: x: 3, y: -1 return 0; } ``` -==Python - +== Python ```python -def pldvEliminasi(a1, b1, c1, a2, b2, c2): +def eliminasi_pldv(a1, b1, c1, a2, b2, c2): # Menghitung koefisien untuk eliminasi factor = a2 / a1 # Membuat persamaan baru dengan mengurangi - newB2 = b2 - factor * b1 - newC2 = c2 - factor * c1 + new_b2 = b2 - factor * b1 + new_c2 = c2 - factor * c1 # Menyelesaikan untuk y - y = newC2 / newB2 + y = new_c2 / new_b2 # Menghitung x dengan substitusi y ke dalam persamaan 1 x = (c1 - b1 * y) / a1 @@ -323,7 +346,34 @@ def pldvEliminasi(a1, b1, c1, a2, b2, c2): return x, y # Contoh: 2x - 3y = 7 dan 3x - 2y = 8 -x, y = pldvEliminasi(2, 3, 7, 3, -2, 8) +x, y = eliminasi_pldv(2, 3, 7, 3, -2, 8) print(f"x: {x}, y: {y}") # Output: x: 2, y: 1 ``` + +== Rust +```rust +fn eliminasi_pldv(a1: f64, b1: f64, c1: f64, a2: f64, b2: f64, c2: f64) -> (f64, f64) { + // Menghitung koefisien untuk eliminasi + let factor = a2 / a1; + + // Membuat persamaan baru dengan mengurangi + let new_b2 = b2 - factor * b1; + let new_c2 = c2 - factor * c1; + + // Menyelesaikan untuk y + let y = new_c2 / new_b2; + + // Menghitung x dengan substitusi y ke dalam persamaan 1 + let x = (c1 - b1 * y) / a1; + + (x, y) +} + +fn main() { + // Contoh: 2x - 3y = 7 dan 3x - 2y = 8 + let (x, y) = eliminasi_pldv(2.0, 3.0, 7.0, 3.0, -2.0, 8.0); + println!("x: {}, y: {}", x, y); // Output: x: 2, y: 1 +} +``` + ::: diff --git a/docs/algebra/quadratic-equation.md b/docs/id/algebra/quadratic-equation.md similarity index 53% rename from docs/algebra/quadratic-equation.md rename to docs/id/algebra/quadratic-equation.md index 72385b8..ad22862 100644 --- a/docs/algebra/quadratic-equation.md +++ b/docs/id/algebra/quadratic-equation.md @@ -35,7 +35,7 @@ $$D = b^2 - 4ac$$ Dimana $a$, $b$, dan $c$ adalah koefisien dari persamaan kuadrat $ax^2 + bx + c = 0$. Berikut adalah beberapa kemungkinan nilai diskriminan: -- Jika $D > 0$, maka persamaan kuadrat memiliki solusi bilangan real +- Jika $D > 0$, maka persamaan kuadrat memiliki solusi bilangan real. - Jika $D = 0$, maka persamaan kuadrat memiliki dua akar real yang sama. - Jika $D < 0$, maka persamaan kuadrat memiliki dua akar kompleks. @@ -60,33 +60,34 @@ Yang akhirnya menjadi $x = 4$ atau $x = -1$. Jadi, akar-akar dari persamaan $x^2 Jika diimplementasikan dalam kode, maka hasilnya adalah seperti ini: -:::tabs -==Javascript - +:::tabs key:lang +== Javascript ```js -function findRootsStepByStep(a, b, c) { +function cari_akar_persamaan(a, b, c) { // Langkah 1: Hitung b^2 dan 4ac - const bSquared = b * b; - const fourAC = 4 * a * c; + const b_squared = b * b; + const four_ac = 4 * a * c; + // Langkah 2: Hitung diskriminan - const discriminant = bSquared - fourAC; + const discriminant = b_squared - four_ac; if (discriminant >= 0) { // Jika diskriminan >= 0, lanjutkan dengan akar real // Langkah 3: Hitung akar dari diskriminan - const sqrtDiscriminant = Math.sqrt(discriminant); - // Langkah 4: Hitung dua kemungkinan nilai untuk x - const root1 = (-b + sqrtDiscriminant) / (2 * a); - const root2 = (-b - sqrtDiscriminant) / (2 * a); - console.log(`x1 = (-${b} + ${sqrtDiscriminant}) / (2 * ${a}) = ${root1}`); - console.log(`x2 = (-${b} - ${sqrtDiscriminant}) / (2 * ${a}) = ${root2}`); + const sqrt_discriminant = Math.sqrt(discriminant); + + // Langkah 4: Hitung dua kemungkinan nilai untuk x + const root1 = (-b + sqrt_discriminant) / (2 * a); + const root2 = (-b - sqrt_discriminant) / (2 * a); + console.log(`x1 = (-${b} + ${sqrt_discriminant}) / (2 * ${a}) = ${root1}`); + console.log(`x2 = (-${b} - ${sqrt_discriminant}) / (2 * ${a}) = ${root2}`); console.log(`Akar-akarnya adalah: x1 = ${root1} dan x2 = ${root2}`); } else { // Jika diskriminan < 0, akar kompleks - const realPart = -b / (2 * a); - const imaginaryPart = Math.sqrt(-discriminant) / (2 * a); - console.log(`x1 = ${realPart} + ${imaginaryPart}i`); - console.log(`x2 = ${realPart} - ${imaginaryPart}i`); + const real_part = -b / (2 * a); + const imaginary_part = Math.sqrt(-discriminant) / (2 * a); + console.log(`x1 = ${real_part} + ${imaginary_part}i`); + console.log(`x2 = ${real_part} - ${imaginary_part}i`); } } @@ -94,84 +95,81 @@ function findRootsStepByStep(a, b, c) { const a = 1; const b = -3; const c = -4; -findRootsStepByStep(a, b, c); +cari_akar_persamaan(a, b, c); ``` == C++ - ```cpp -import kotlin.math.sqrt +#include +#include -fun akarPersamaan(a: Double, b: Double, c: Double) { +fun cari_akar_persamaan(a: Double, b: Double, c: Double) { // Langkah 1: Hitung bagian-bagian dari rumus - val bSquared = b * b - val fourAC = 4 * a * c + val b_squared = b * b; + val four_ac = 4 * a * c; // Langkah 2: Hitung diskriminan - val discriminant = bSquared - fourAC + val discriminant = b_squared - four_ac; if (discriminant >= 0) { // Jika diskriminan >= 0, lanjutkan dengan akar real // Langkah 3: Hitung akar dari diskriminan - val sqrtDiscriminant = sqrt(discriminant) + val sqrt_discriminant = sqrt(discriminant); // Langkah 4: Hitung dua kemungkinan nilai untuk x - val root1 = (-b + sqrtDiscriminant) / (2 * a) - val root2 = (-b - sqrtDiscriminant) / (2 * a) - println("x1 = (-$b + $sqrtDiscriminant) / (2 * $a) = $root1") - println("x2 = (-$b - $sqrtDiscriminant) / (2 * $a) = $root2") + val root1 = (-b + sqrt_discriminant) / (2 * a); + val root2 = (-b - sqrt_discriminant) / (2 * a); + println("x1 = (-$b + $sqrt_discriminant) / (2 * $a) = $root1"); + println("x2 = (-$b - $sqrt_discriminant) / (2 * $a) = $root2"); // Tampilkan hasil akhirnya - println("Akar-akarnya adalah: x1 = $root1 dan x2 = $root2") + println("Akar-akarnya adalah: x1 = $root1 dan x2 = $root2"); } else { // Jika diskriminan < 0, akar kompleks - val realPart = -b / (2 * a) - val imaginaryPart = sqrt(-discriminant) / (2 * a) - println("x1 = $realPart + ${imaginaryPart}i") - println("x2 = $realPart - ${imaginaryPart}i") + val real_part = -b / (2 * a); + val imaginary_part = sqrt(-discriminant) / (2 * a); + println("x1 = $real_part + ${imaginary_part}i"); + println("x2 = $real_part - ${imaginary_part}i"); } } fun main() { // Contoh untuk persamaan x^2 - 3x - 4 = 0 - val a = 1.0 - val b = -3.0 - val c = -4.0 - akarPersamaan(a, b, c) + val a = 1.0; + val b = -3.0; + val c = -4.0; + cari_akar_persamaan(a, b, c); } - ``` - == Kotlin - ```kotlin import kotlin.math.sqrt -fun akarPersamaan(a: Double, b: Double, c: Double) { +fun cari_akar_persamaan(a: Double, b: Double, c: Double) { // Langkah 1: Hitung bagian-bagian dari rumus - val bSquared = b * b - val fourAC = 4 * a * c + val b_squared = b * b + val four_ac = 4 * a * c // Langkah 2: Hitung diskriminan - val discriminant = bSquared - fourAC + val discriminant = b_squared - four_ac if (discriminant >= 0) { // Jika diskriminan >= 0, lanjutkan dengan akar real // Langkah 3: Hitung akar dari diskriminan - val sqrtDiscriminant = sqrt(discriminant) + val sqrt_discriminant = sqrt(discriminant) // Langkah 4: Hitung dua kemungkinan nilai untuk x - val root1 = (-b + sqrtDiscriminant) / (2 * a) - val root2 = (-b - sqrtDiscriminant) / (2 * a) - println("x1 = (-$b + $sqrtDiscriminant) / (2 * $a) = $root1") - println("x2 = (-$b - $sqrtDiscriminant) / (2 * $a) = $root2") + val root1 = (-b + sqrt_discriminant) / (2 * a) + val root2 = (-b - sqrt_discriminant) / (2 * a) + println("x1 = (-$b + $sqrt_discriminant) / (2 * $a) = $root1") + println("x2 = (-$b - $sqrt_discriminant) / (2 * $a) = $root2") println("Akar-akarnya adalah: x1 = $root1 dan x2 = $root2") } else { // Jika diskriminan < 0, akar kompleks - val realPart = -b / (2 * a) - val imaginaryPart = sqrt(-discriminant) / (2 * a) - println("x1 = $realPart + ${imaginaryPart}i") - println("x2 = $realPart - ${imaginaryPart}i") + val real_part = -b / (2 * a) + val imaginary_part = sqrt(-discriminant) / (2 * a) + println("x1 = $real_part + ${imaginary_part}i") + println("x2 = $real_part - ${imaginary_part}i") } } @@ -180,40 +178,83 @@ fun main() { val a = 1.0 val b = -3.0 val c = -4.0 - akarPersamaan(a, b, c) + cari_akar_persamaan(a, b, c) } ``` == Python ``` python import math -def findRootsStepByStep(a, b, c): +def cari_akar_persamaan(a, b, c): # Langkah 1: Hitung b^2 dan 4ac - bSquared = b * b - fourAC = 4 * a * c + b_squared = b * b + four_ac = 4 * a * c + # Langkah 2: Hitung diskriminan - discriminant = bSquared - fourAC + discriminant = b_squared - four_ac if discriminant >= 0: # Jika diskriminan >= 0, lanjutkan dengan akar real # Langkah 3: Hitung akar dari diskriminan - sqrtDiscriminant = math.sqrt(discriminant) + sqrt_discriminant = math.sqrt(discriminant) + # Langkah 4: Hitung dua kemungkinan nilai untuk x - root1 = (-b + sqrtDiscriminant) / (2 * a) - root2 = (-b - sqrtDiscriminant) / (2 * a) - print(f"x1 = (-{b} + {sqrtDiscriminant}) / (2 * {a}) = {root1}") - print(f"x2 = (-{b} - {sqrtDiscriminant}) / (2 * {a}) = {root2}") + root1 = (-b + sqrt_discriminant) / (2 * a) + root2 = (-b - sqrt_discriminant) / (2 * a) + print(f"x1 = (-{b} + {sqrt_discriminant}) / (2 * {a}) = {root1}") + print(f"x2 = (-{b} - {sqrt_discriminant}) / (2 * {a}) = {root2}") print(f"Akar-akarnya adalah: x1 = {root1} dan x2 = {root2}") else: # Jika diskriminan < 0, akar kompleks - realPart = -b / (2 * a) - imaginaryPart = math.sqrt(-discriminant) / (2 * a) - print(f"x1 = {realPart} + {imaginaryPart}i") - print(f"x2 = {realPart} - {imaginaryPart}i") + real_part = -b / (2 * a) + imaginary_part = math.sqrt(-discriminant) / (2 * a) + print(f"x1 = {real_part} + {imaginary_part}i") + print(f"x2 = {real_part} - {imaginary_part}i") # Contoh untuk persamaan x^2 - 3x - 4 = 0 a = 1 b = -3 c = -4 -findRootsStepByStep(a, b, c) -``` \ No newline at end of file +cari_akar_persamaan(a, b, c) +``` +== Rust +```rust +fn cari_akar_persamaan(a: f64, b: f64, c: f64) { + // Langkah 1: Hitung bagian-bagian dari rumus + let b_squared = b * b; + let four_ac = 4.0 * a * c; + + // Langkah 2: Hitung diskriminan + let discriminant = b_squared - four_ac; + + if discriminant >= 0.0 { + // Jika diskriminan >= 0, lanjutkan dengan akar real + // Langkah 3: Hitung akar dari diskriminan + let sqrt_discriminant = discriminant.sqrt(); + + // Langkah 4: Hitung dua kemungkinan nilai untuk x + let root1 = (-b + sqrt_discriminant) / (2.0 * a); + let root2 = (-b - sqrt_discriminant) / (2.0 * a); + println!("x1 = (-{} + {}) / (2 * {}) = {}", b.abs(), sqrt_discriminant, a, root1); + println!("x2 = (-{} - {}) / (2 * {}) = {}", b.abs(), sqrt_discriminant, a, root2); + + // Tampilkan hasil akhirnya + println!("Akar-akarnya adalah: x1 = {} dan x2 = {}", root1, root2); + } else { + // Jika diskriminan < 0, akar kompleks + let real_part: f64 = -b / (2.0 * a); + let imaginary_part = -discriminant.sqrt() / (2.0 * a); + println!("x1 = {} + {}", real_part, imaginary_part); + println!("x2 = {} - {}", real_part, imaginary_part); + } +} + +fun main() { + // Contoh untuk persamaan x^2 - 3x - 4 = 0 + let a = 1.0; + let b = -3.0; + let c = -4.0; + cari_akar_persamaan(a, b, c); +} +``` +::: diff --git a/docs/arithmetic/factors.md b/docs/id/arithmetic/factors.md similarity index 66% rename from docs/arithmetic/factors.md rename to docs/id/arithmetic/factors.md index e7cd22f..9b440f3 100644 --- a/docs/arithmetic/factors.md +++ b/docs/id/arithmetic/factors.md @@ -48,46 +48,49 @@ Dari pohon faktor diatas kita bisa lihat bahwa faktorisasi dari 100 adalah $2 \t Kalo di pemrograman kita bisa pake _loop_ dan [modulo](/arithmetic/operation-on-number#modulus) untuk mencari faktorisasi dari suatu bilangan. Berikut contoh implementasinya: -:::tabs +:::tabs key:lang == Javascript ```js -function faktorisasi(bilangan) { +function hitung_faktorisasi(bilangan) { let faktor = 2; - let faktorisasi = []; + let hasil_faktorisasi = []; while (bilangan > 1) { if (bilangan % faktor === 0) { - faktorisasi.push(faktor); + hasil_faktorisasi.push(faktor); bilangan /= faktor; } else { faktor++; } } - return faktorisasi; + return hasil_faktorisasi; } -let faktorisasi100 = faktorisasi(100); // [2, 2, 5, 5] +let faktorisasi_100 = hitung_faktorisasi(100); +console.log(faktorisasi_100); // [2, 2, 5, 5] ``` == Kotlin ```kt -fun faktorisasi(bilangan: Int): List { +fun hitung_faktorisasi(bilangan: Int): List { var faktor = 2 - val faktorisasi = mutableListOf() + val hasil_faktorisasi = mutableListOf() var bilangan = bilangan while (bilangan > 1) { if (bilangan % faktor == 0) { - faktorisasi.add(faktor) + hasil_faktorisasi.add(faktor) bilangan /= faktor } else { faktor++ } } - return faktorisasi + return hasil_faktorisasi } -val faktorisasi100 = faktorisasi(100) // [2, 2, 5, 5] +val faktorisasi_100 = hitung_faktorisasi(100) +println(faktorisasi_100) // [2, 2, 5, 5] + ``` == C++ @@ -96,42 +99,64 @@ val faktorisasi100 = faktorisasi(100) // [2, 2, 5, 5] #include #include -std::vector faktorisasi(int bilangan) { +std::vector hitung_faktorisasi(int bilangan) { int faktor = 2; - std::vector faktorisasi; + std::vector hasil_faktorisasi; while (bilangan > 1) { if (bilangan % faktor == 0) { - faktorisasi.push_back(faktor); + hasil_faktorisasi.push_back(faktor); bilangan /= faktor; } else { faktor++; } } - return faktorisasi; + return hasil_faktorisasi; } int main() { - std::vector faktorisasi100 = faktorisasi(100); // [2, 2, 5, 5] + std::vector faktorisasi_100 = hitung_faktorisasi(100); // [2, 2, 5, 5] return 0; } ``` == Python ```python -def faktorisasi(bilangan): +def hitung_faktorisasi(bilangan): faktor = 2 - faktorisasi = [] + hasil_faktorisasi = [] while bilangan > 1: if bilangan % faktor == 0: - faktorisasi.append(faktor) + hasil_faktorisasi.append(faktor) bilangan /= faktor else: faktor += 1 - return faktorisasi + return hasil_faktorisasi -faktorisasi100 = faktorisasi(100) # [2, 2, 5, 5] +faktorisasi_100 = hitung_faktorisasi(100) +print (faktorisasi_100) # [2, 2, 5, 5] ``` +== Rust +```rust +fn hitung_faktorisasi(mut bilangan: f64) -> Vec { + let mut faktor = 2.0; + let mut hasil_faktorisasi = vec![]; + while bilangan > 1.0 { + if bilangan % faktor == 0.0 { + hasil_faktorisasi.push(faktor); + bilangan /= faktor; + } else { + faktor += 1.0; + } + } + hasil_faktorisasi +} + +fn main() { + let faktorisasi_100 = hitung_faktorisasi(100); + println!("{:?}", faktorisasi_100); // [2.0, 2.0, 5.0, 5.0] +} +``` ::: Btw diatas kita pakai `/=` itu sama aja dengan `bilangan = bilangan / faktor`, sama aja kaya `+= -= *=` yang biasa kita pakai. @@ -148,64 +173,80 @@ Misalnya lagi jika $a = 3$ maka kelipatan dari 3 adalah: - dan seterusnya... Jika kelipatan diimplementasikan dalam pemrograman, kita bisa menggunakan _loop_ untuk melakukan perkalian berulang. Contohnya seperti ini: -:::tabs +:::tabs key:lang == Javascript ```js -function kelipatan(a, n) { - let kelipatan = []; +function hitung_kelipatan(a, n) { + let hasil_kelipatan = []; for (let i = 1; i <= n; i++) { - kelipatan.push(a * i); + hasil_kelipatan.push(a * i); } - return kelipatan; + return hasil_kelipatan; } -let kelipatan3 = kelipatan(3, 5); // [3, 6, 9, 12, 15] +let kelipatan3 = hitung_kelipatan(3, 5); +console.log(kelipatan3); // [3, 6, 9, 12, 15] ``` == Kotlin ```kt -fun kelipatan(a: Int, n: Int): List { - val kelipatan = mutableListOf() +fun hitung_kelipatan(a: Int, n: Int): List { + val hasil_kelipatan = mutableListOf() for (i in 1..n) { - kelipatan.add(a * i) + hasil_kelipatan.add(a * i) } - return kelipatan + return hasil_kelipatan } -val kelipatan3 = kelipatan(3, 5) // [3, 6, 9, 12, 15] +val kelipatan3 = hitung_kelipatan(3, 5) +println(kelipatan3) // [3, 6, 9, 12, 15] ``` == C++ ```cpp -std::vector kelipatan(int a, int n) { - std::vector kelipatan; +std::vector hitung_kelipatan(int a, int n) { + std::vector hasil_kelipatan; for (int i = 1; i <= n; i++) { - kelipatan.push_back(a * i); + hasil_kelipatan.push_back(a * i); } - return kelipatan; + return hasil_kelipatan; } int main() { - std::vector kelipatan3 = kelipatan(3, 5); // [3, 6, 9, 12, 15] + std::vector kelipatan3 = hitung_kelipatan(3, 5); // [3, 6, 9, 12, 15] return 0; } ``` == Python ```python -def kelipatan(a, n): - kelipatan = [] +def hitung_kelipatan(a, n): + hasil_kelipatan = [] for i in range(1, n+1): - kelipatan.append(a * i) - - return kelipatan + hasil_kelipatan.append(a * i) + return hasil_kelipatan -kelipatan3 = kelipatan(3, 5) +hasil = hitung_kelipatan(3, 5) +print (hasil) # [3, 6, 9, 12, 15] +``` +== Rust +```rust +fn hitung_kelipatan(a: u64, n: u64) -> Vec { + let mut hasil_kelipatan = vec![]; + for i in 1..(n + 1) { + hasil_kelipatan.push(a * i); + } + hasil_kelipatan +} +fn main() { + let hasil = hitung_kelipatan(3, 5); + println!("{:?}", hasil); // [3, 6, 9, 12, 15] +} ``` ::: -## Faktor Persekutuan Terbesar (FPB) +## Faktor Persekutuan Terbesar (FPB) FPB itu angka terbesar yang bisa membagi dua bilangan tanpa sisa. FPB biasanya dipakai untuk mencari kesamaan dari dua bilangan yang berbeda. @@ -229,11 +270,11 @@ Cara ngitungnya kek gini: 5. Kalo $r$ udah 0, maka FPB dari $a$ dan $b$ adalah $b$. Pusing? Tenang, mari jadiin kode aja biar lebih mudah dimengerti kek gini: -:::tabs +:::tabs key:lang == Javascript ```javascript -function fpb(a, b) { +function hitung_fpb(a, b) { while (b !== 0) { let t = b; b = a % b; @@ -242,12 +283,13 @@ function fpb(a, b) { return a; } -let fpb1218 = fpb(12, 18); // 6 +let fpb_1218 = hitung_fpb(12, 18); +console.log(fpb_1218); // 6 ``` == Kotlin ```kotlin -fun fpb(a: Int, b: Int): Int { +fun hitung_fpb(a: Int, b: Int): Int { var a = a var b = b while (b != 0) { @@ -258,12 +300,15 @@ fun fpb(a: Int, b: Int): Int { return a } -val fpb1218 = fpb(12, 18) // 6 +val fpb_1218 = hitung_fpb(12, 18) +println(fpb_1218) // 6 ``` == C++ ```cpp -std::vector fpb(int a, int b) { +#include + +std::vector hitung_fpb(int a, int b) { while (b != 0) { int t = b; b = a % b; @@ -273,13 +318,14 @@ std::vector fpb(int a, int b) { } int main() { - int fpb1218 = fpb(12, 18); // 6 + int fpb_1218 = hitung_fpb(12, 18); + std::cout << fpb_1218 << std::endl; // 6 return 0; } ``` == Python ```python -def fpb(a, b): +def hitung_fpb(a, b): while b != 0: t = b b = a % b @@ -287,7 +333,24 @@ def fpb(a, b): return a -fpb1218 = fpb(12, 18) # 6 +fpb_1218 = hitung_fpb(12, 18) +print (fpb_1218) # 6 +``` +== Rust +```rust +fn hitung_fpb(mut a: u64, mut b: u64) -> u64 { + while b != 0 { + let t = b; + b = a % b; + a = t + } + a +} + +fn main() { + let fpb_1218 = hitung_fpb(12, 18); + println!("{}", fpb_1218); // 6 +} ``` ::: @@ -320,43 +383,60 @@ Kalian bebas sih pake yang mana, yang penting gak salah. Gampang kan? Mari kita jadiin kode biar lebih mudah dimengerti: -:::tabs +:::tabs key:lang == Javascript ```javascript -function kpk(a, b) { - return (a * b) / fpb(a, b); +function hitung_kpk(a, b) { + return (a * b) / hitung_fpb(a, b); } -let kpk1218 = kpk(12, 18); // 36 +let kpk_1218 = hitung_kpk(12, 18); +console.log(kpk_1218); // 36 ``` == Kotlin ```kotlin -fun kpk(a: Int, b: Int): Int { - return (a * b) / fpb(a, b) +fun hitung_kpk(a: Int, b: Int): Int { + return (a * b) / hitung_fpb(a, b) } -val kpk1218 = kpk(12, 18) // 36 +val kpk_1218 = hitung_kpk(12, 18) // 36 +println(kpk_1218) // 36 ``` == C++ ```cpp -int kpk(int a, int b) { - return (a * b) / fpb(a, b); +#include + +int hitung_kpk(int a, int b) { + return (a * b) / hitung_fpb(a, b); } int main() { - int kpk1218 = kpk(12, 18); // 36 + int kpk_1218 = hitung_kpk(12, 18); + std::cout << kpk_1218 << std::endl; // 36 return 0; } ``` == Python ```python -def kpk(a, b): - return (a * b) / fpb(a, b) +def hitung_kpk(a, b): + return (a * b) / hitung_fpb(a, b) -kpk1218 = kpk(12, 18) # 36.0 +kpk_1218 = hitung_kpk(12, 18) +print (kpk_1218) # 36.0 +``` +== Rust +```rust +fn hitung_kpk(a: u64, b: u64) -> u64 { + (a * b) / hitung_fpb(a, b) +} + +fn main() { + let kpk_1218 = hitung_kpk(12, 18); + println!("{}", kpk_1218); // 36 +} ``` ::: diff --git a/docs/arithmetic/numbers.md b/docs/id/arithmetic/numbers.md similarity index 75% rename from docs/arithmetic/numbers.md rename to docs/id/arithmetic/numbers.md index 8f66e0b..fb65a35 100644 --- a/docs/arithmetic/numbers.md +++ b/docs/id/arithmetic/numbers.md @@ -1,9 +1,9 @@ --- title: Bilangan -description: Contoh penggunaan Bilangan dalam pemrograman +description: Contoh penggunaan Bilangan dalam pemrograman --- -# Bilangan +# Bilangan Bilangan merupakan dasar dari matematika, semuanya di matematika pake bilangan. Dalam pemrograman, bilangan juga sangat penting. Kita bisa melakukan berbagai operasi matematika dengan bilangan, seperti penjumlahan, pengurangan, perkalian, dan pembagian. @@ -13,37 +13,41 @@ Namun bilangan di pemrograman dibagi-bagi ke beberapa jenis, tergantung dari tip Bilangan bulat adalah bilangan yang tidak punya koma. Di pemrograman, bilangan bulat biasanya disebut dengan `integer`. Contoh bilangan bulat adalah 1, 2, 3, 4, 5, dan seterusnya. -:::tabs +:::tabs key:lang == Javascript ```js -let bilanganBulat = 10; +let bilangan_bulat = 10; ``` == Kotlin ```kt -val bilanganBulat: Int = 10 +val bilangan_bulat: Int = 10 ``` == C++ ```cpp -int bilanganBulat = 10; +int bilangan_bulat = 10; ``` == Python ```python -bilanganBulat = 10 +bilangan_bulat = 10 +``` +== Rust +```rust +let bilangan_bulat = 10; ``` ::: -Meski kelihatannya sederhana, jangan lupa kalau di pemrograman, bilangan punya batasan! Contohnya, di Javascript, bilangan paling besar yang bisa kamu pakai adalah **`9,007,199,254,740,992`**. Itu setara dengan angka yang sangat besar seriously, aku aja bingung ngucapinnya. +Meski kelihatannya sederhana, jangan lupa kalau di pemrograman, bilangan punya batasan! Contohnya, di Rust, bilangan paling besar yang bisa kamu pakai adalah **`340,282,366,920,938,463,463,374,607,431,768,211,455`** atau $2^{128} - 1$. Itu angka yang sangat besar, aku aja bingung ngucapinnya. -Nah, kalau di C++ dan bahasa lain yang punya tipe data lebih banyak daripada JS (cuman `number` dan `BigInt`), batasan itu tergantung tipe data yang kamu pakai. Contoh kalo pake `short` di c++, kamu bisa mencapai angka **`32,767`** terkecuali di python, python tidak memiliki batas bilangan bulat, karena Python secara dinamis menangani ukuran bilangan bulat. contohnya seperti dibawah ini +Nah, batasan itu tergantung tipe data yang kamu pakai kecuali di python, python tidak memiliki batas bilangan bulat, karena Python secara dinamis menangani ukuran bilangan bulat. contohnya seperti dibawah ini -:::tabs +:::tabs key:lang == Javascript | Tipe Data | Ukuran (bits) | Minimal| Maksimal| Maksimal (Secara Eksplisit) | |-----------|------------------|---------------|----|---------------------------| | Number | 64 | -9,007,199,254,740,991
(−253 - 1) | 9,007,199,254,740,992
(253 - 1 ) | 18,446,744,073,709,551,616 (264) | | BigInt | max 1,000,000,000 | `tergantung memori` | `tergantung memori` | `tergantung memori` | -== C++ +== C++ | Tipe Data | Ukuran (bits) | Minimal | Maksimal | Maksimal (Secara Eksplisit) |-----------|------------------|------------------------------------------------|-----------------------------------------------|---------------------------| | `short` | 16 | -32,768 | 32,767 | 65,536 (216) | @@ -65,30 +69,34 @@ Banyak banget selengkapnya cek [sini aja ya](https://learn.microsoft.com/en-us/c Bilangan desimal atau floating point adalah bilangan yang punya koma. Di pemrograman, bilangan desimal biasanya disebut dengan `float` atau `double`. Contoh bilangan desimal adalah 1.5, 2.3, 3.14, dan seterusnya. Untuk membuat bilangan desimal kamu bisa menggunakan kode seperti dibawah ini -:::tabs +:::tabs key:lang == Javascript ```js -let bilanganDesimal = 3.14; +let bilangan_desimal = 3.14; ``` == Kotlin ```kt -val bilanganDesimal: Float = 3.14F +val bilangan_desimal: Float = 3.14F ``` Kita juga bisa menggunakan `double` untuk bilangan desimal yang memiliki angka di belakang koma lebih banyak (sampe 15 digit). Contoh penggunaannya seperti ini: ```kt -val bilanganDesimal: Double = 3.141592653589793f +val bilangan_desimal: Double = 3.141592653589793f ``` == C++ ```cpp -float bilanganDesimal = 3.14f; +float bilangan_desimal = 3.14f; ``` Kita juga bisa menggunakan `double` untuk bilangan desimal yang memiliki angka di belakang koma lebih banyak (sampe 15 digit). Contoh penggunaannya seperti ini: ```cpp -double bilanganDesimal = 3.141592653589793F; +double bilangan_desimal = 3.141592653589793F; ``` == Python ```python -bilanganDesimal = 3.14 +bilangan_desimal = 3.14 +``` +== Rust +```rust +let bilangan_desimal = 3.14; ``` ::: @@ -97,51 +105,61 @@ bilanganDesimal = 3.14 Bilangan pecahan adalah bilangan yang punya pembilang dan penyebut. Di pemrograman, bilangan pecahan biasanya disebut dengan `fraction`. Contoh bilangan pecahan adalah 1/2, 3/4, 5/6, dan seterusnya. Sayangnya di pemrograman, bilangan pecahan gak ada tipe datanya tapi langsung dihitung aja yang nantinya hasilnya bakal jadi bilangan desimal. Contoh penggunaannya seperti ini: -:::tabs +:::tabs key:lang == Javascript ```js -let bilanganPecahan = 1/2; +let bilangan_pecahan = 1 / 2; ``` == Kotlin ```kt -val bilanganPecahan = 1/2 // Otomatis jadi float +val bilangan_pecahan = 1 / 2 // Otomatis jadi float ``` == C++ ```cpp -float bilanganPecahan = 1/2; +float bilangan_pecahan = 1 / 2; ``` == Python ```python -bilanganPecahan = 1/2 +bilangan_pecahan = 1 / 2 ``` +== Rust +```rust +let bilangan_pecahan = 1.0 / 2.0; +``` + +Berbeda dengan Kotlin, di mana nilai dapat otomatis berubah menjadi float, Rust dan beberapa bahasa pemrograman lainnya sensitif terhadap tipe data. Misalnya, jika kita menggunakan `1 / 2`, hasilnya akan `0` karena `1` merupakan integer. Untuk mendapatkan hasil sebagai float, kita perlu menambahkan `.0` di belakangnya. ::: > [!WARNING] Perhatian saat melakukan operasi dengan bilangan pecahan dan desimal > Dalam banyak bahasa pemrograman, termasuk JavaScript, ada yang disebut dengan `floating point error`, yang dapat menyebabkan hasil perhitungan tidak akurat. Hal ini terjadi karena bilangan desimal tidak selalu dapat direpresentasikan secara tepat dalam format biner. -> +> > Contoh, ketika kita menjumlahkan 0.1 dan 0.2 di JavaScript, hasilnya bukan 0.3, melainkan 0.30000000000000004. Ini disebabkan oleh keterbatasan representasi angka desimal dalam komputer. -> -> Untuk menghindari masalah ini, sebaiknya batasi presisi hasil perhitungan dengan cara Membulatkan hasil ke jumlah angka desimal yang diinginkan (misalnya dengan `toFixed()` atau `Math.round()`. -> +> +> Untuk menghindari masalah ini, sebaiknya batasi presisi hasil perhitungan dengan cara Membulatkan hasil ke jumlah angka desimal yang diinginkan (misalnya dengan `toFixed()` atau `Math.round()`. +> > Kamu juga bisa menggunakan pustaka seperti BigNumber atau yang lainnya Gimana dengan **Bilangan pecahan campuran** kan di matematika ada kaya $1\frac{1}{2}$, di pemrograman juga bisa kok. Kita bisa menggunakan `float` atau `double` untuk bilangan pecahan campuran. Contoh penggunaannya seperti ini: -:::tabs +:::tabs key:lang == Javascript ```js -let bilanganPecahanCampuran = 1 + 1/2; +let bilangan_pecahan_campuran = 1 + 1 / 2; ``` == Kotlin ```kt -val bilanganPecahanCampuran: Double = 1 + 1/2 +val bilangan_pecahan_campuran: Double = 1 + 1 / 2 ``` == C++ ```cpp -double bilanganPecahanCampuran = 1 + 1/2; +double bilangan_pecahan_campuran = 1 + 1 / 2; ``` == Python ```python -bilanganPecahanCampuran = 1 + 1/2 +bilangan_pecahan_campuran = 1 + 1 / 2 +``` +== Rust +```rust +let bilangan_pecahan_campuran = 1.0 + 1.0 / 2.0; ``` ::: diff --git a/docs/arithmetic/operation-on-number.md b/docs/id/arithmetic/operation-on-number.md similarity index 67% rename from docs/arithmetic/operation-on-number.md rename to docs/id/arithmetic/operation-on-number.md index a455504..20a45fe 100644 --- a/docs/arithmetic/operation-on-number.md +++ b/docs/id/arithmetic/operation-on-number.md @@ -12,42 +12,51 @@ Operasi bilangan atau proses untuk memanipulasi nilai numerik tertentu pake tekn Di pemrograman, kita bisa melakukan berbagai operasi matematika dengan bilangan. Ada penjumlahan, pengurangan, perkalian, dan pembagian. Berbeda dengan matematika biasa yang pakai simbol `+`, `-`, `*`, dan `/`, di pemrograman kita pakai simbol yang berbeda. Contoh penggunaannya seperti ini: -:::tabs +:::tabs key:lang == Javascript ```js let a = 10; let b = 5; -let hasilPenjumlahan = a + b; // 15 -let hasilPengurangan = a - b; // 5 -let hasilPerkalian = a * b; // 50 -let hasilPembagian = a / b; // 2 +let hasil_penjumlahan = a + b; // 15 +let hasil_pengurangan = a - b; // 5 +let hasil_perkalian = a * b; // 50 +let hasil_pembagian = a / b; // 2 ``` == Kotlin ```kt val a = 10 val b = 5 -val hasilPenjumlahan = a + b // 15 -val hasilPengurangan = a - b // 5 -val hasilPerkalian = a * b // 50 -val hasilPembagian = a / b // 2 +val hasil_penjumlahan = a + b // 15 +val hasil_pengurangan = a - b // 5 +val hasil_perkalian = a * b // 50 +val hasil_pembagian = a / b // 2 ``` == C++ ```cpp int a = 10; int b = 5; -int hasilPenjumlahan = a + b; // 15 -int hasilPengurangan = a - b; // 5 -int hasilPerkalian = a * b; // 50 -int hasilPembagian = a / b; // 2 +int hasil_penjumlahan = a + b; // 15 +int hasil_pengurangan = a - b; // 5 +int hasil_perkalian = a * b; // 50 +int hasil_pembagian = a / b; // 2 ``` == Python ```python a = 10 b = 5 -hasilPenjumlahan = a + b # 15 -hasilPengurangan = a - b # 5 -hasilPerkalian = a * b # 50 -hasilPembagian = a / b # 2 +hasil_penjumlahan = a + b # 15 +hasil_pengurangan = a - b # 5 +hasil_perkalian = a * b # 50 +hasil_pembagian = a / b # 2 +``` +== Rust +```rust +let a = 10; +let b = 5; +let hasil_penjumlahan = a + b; // 15 +let hasil_pengurangan = a - b; // 5 +let hasil_perkalian = a * b; // 50 +let hasil_pembagian = a as f64 / b as f64; // 2.0 ``` ::: @@ -59,7 +68,7 @@ Di atas kita menggunakan simbol `/` untuk pembagian dan `*` untuk perkalian. Ini ## Pangkat (Exponentiation) Pangkat adalah operasi matematika yang digunakan untuk menghitung hasil perkalian bilangan dengan dirinya sendiri sebanyak $n$ kali. Di pemrograman, kita bisa menggunakan operator `**` ataupun pakai `pow()` untuk menghitung pangkat. Contoh penggunaannya seperti ini: -:::tabs +:::tabs key:lang == Javascript ```js let pangkat = 2 ** 3; // 8 @@ -86,6 +95,14 @@ int main() { pangkat = 2 ** 3 # 8 pangkat2 = pow(2, 3) # 8 ``` +== Rust +```rust +let pangkat = 2_u64.pow(3); // 8 +let pangkat2 = 2.0_f64.powf(3.0); // 8.0 +``` +> [!NOTE] +> Dalam Rust, `powf` bukanlah kesalahan pengetikan, melainkan nama fungsi yang digunakan untuk bilangan float. Jika kamu ingin melakukan operasi pangkat pada bilangan bulat, gunakan fungsi `pow`. Untuk bilangan float, gunakan `powf`. + ::: `pow()` biasanya meminta dua parameter, parameter pertama adalah bilangan yang mau dipangkatkan, dan parameter kedua adalah pangkatnya. jadi kalo kita mau menghitung $2^3$ kita bisa tulis `pow(2, 3)`. @@ -122,18 +139,23 @@ import math akar = math.sqrt(16) # 4.0 ``` +Untuk Rust, kita tidak perlu menggunakan library tambahan untuk menghitung akar kuadrat. Kita bisa memanfaatkan fungsi `sqrt` yang sudah tersedia pada tipe data float. Berikut adalah contohnya: +```rust +let akar = 16.0_f64.sqrt(); // 4.0 +``` + Tapi ada masalah kalo kita mau menghitung akar yang lebih dari 2 kaya $\sqrt[3]{8}$ atau $\sqrt[4]{16}$, Nah untuk kasus ini kita bisa pangkatkan aja bilangannya dengan $1/n$ dimana si $n$ itu adalah akar yang kita mau. Contoh penggunaannya seperti ini: -:::tabs +:::tabs key:lang == Javascript ```js -let akar3 = Math.pow(8, 1/3); // 2 -let akar4 = Math.pow(16, 1/4); // 2 +let akar3 = Math.pow(8, 1 / 3); // 2 +let akar4 = Math.pow(16, 1 / 4); // 2 ``` == Kotlin ```kt -val akar3 = Math.pow(8.0, 1.0/3.0) // 2.0 -val akar4 = Math.pow(16.0, 1.0/4.0) // 2.0 +val akar3 = Math.pow(8.0, 1.0 / 3.0) // 2.0 +val akar4 = Math.pow(16.0, 1.0 / 4.0) // 2.0 ``` == C++ ```cpp @@ -141,8 +163,8 @@ val akar4 = Math.pow(16.0, 1.0/4.0) // 2.0 #include int main() { - double akar3 = pow(8, 1.0/3); // 2 - double akar4 = pow(16, 1.0/4); // 2 + double akar3 = pow(8, 1.0 / 3); // 2 + double akar4 = pow(16, 1.0 / 4); // 2 std::cout << akar3 << std::endl; std::cout << akar4 << std::endl; return 0; @@ -150,35 +172,95 @@ int main() { ``` == Python ```python -akar3 = pow(8, 1/3) # 2.0 -akar4 = pow(16, 1/4) # 2.0 +akar3 = pow(8, 1 / 3) # 2.0 +akar4 = pow(16, 1 / 4) # 2.0 +``` +== Rust +```rust +let akar3 = 8.0_f64.powf(1.0 / 3.0); // 2.0 +let akar4 = 16.0_f64.powf(1.0 / 4.0); // 2.0 ``` ::: Hal ini bisa terjadi karena apapun bilangan yang memiliki pangkat $1/n$ akan menghasilkan akar dari bilangan tersebut. Jadi kalo kita mau menghitung $\sqrt[3]{8}$ kita bisa tulis `pow(8, 1/3)`. +## Akar (Tanpa Modul) + +Kita bisa juga mencari $\lfloor\sqrt{n}\rfloor$ tanpa memakai modul loh dengan cara memanfaatkan persamaan +$$n = x^2 + a$$ +dengan $x$ adalah perpangkatan terdekat dari $n$ dan sisanya adalah $a$. Sebagai contoh $n = 18$ maka $x = 4$ lalu sisanya kita bisa cari dengan cara $a = n - x^2$. Kalau di kodingan seperti ini +:::tabs key:lang +== Javascript +```js +let n = 18; +let x = 1; +while((x + 1) * (x + 1) <= n){ + x++; +} +let a = n - x * x; +``` +== Kotlin +```kt +val n = 18 +var x = 1 +while ((x + 1) * (x + 1) <= n) { + x++ +} +val a = n - x * x +``` +== C++ +```cpp +int n = 18; +int x = 1; +while((x + 1) * (x + 1) <= n){ + x++; +} +int a = n - x * x; +``` +== Python +```python +n = 18 +x = 1 +while (x + 1) * (x + 1) <= n: + x+=1 +a = n - x * x +``` +== Rust +```rust +let n = 18; +let mut x = 1; +while (x + 1) * (x + 1) <= n { + x += 1; +} +let a = n - x * x; +``` +::: ## Modulus Modulus atau sisa hasil pembagian adalah operasi matematika yang digunakan untuk menghitung sisa hasil pembagian dua bilangan. Misalnya kamu mau tau sisa hasil pembagian 10 dibagi 3, maka hasilnya adalah 1. Di pemrograman, kita bisa menggunakan operator `%` untuk menghitung modulus. Operator ini berguna banget buat ngecek bilangan itu genap, ganjil atau punya pola tertentu. Contoh penggunaannya seperti ini: -:::tabs +:::tabs key:lang == Javascript ```js -let hasilModulus = 10 % 3; // 1 +let hasil_modulus = 10 % 3; // 1 ``` == Kotlin ```kt -val hasilModulus = 10 % 3 // 1 +val hasil_modulus = 10 % 3 // 1 ``` == C++ ```cpp -int hasilModulus = 10 % 3; // 1 +int hasil_modulus = 10 % 3; // 1 ``` == Python ```python -hasilModulus = 10 % 3 # 1 +hasil_modulus = 10 % 3 # 1 +``` +== Rust +```rust +let Hasil_modulus = 10 % 3; // 1 ``` ::: @@ -208,7 +290,7 @@ Jadi, hasil akhirnya adalah **42**. Kalo di pemrograman urutan operasi ini udah di tangani sama bahasanya jadi kamu gak perlu khawatir kalo salah urutan operasi. Kamu cukup teliti aja sama rumus yang akan kamu gunakan. Kalo rumus tadi kita masukkan ke kode maka akan jadi seperti ini. -:::tabs +:::tabs key:lang == Javascript ```js let hasil = 6 + 3 * (2 ** 3 + Math.sqrt(16)); // 42 @@ -220,13 +302,17 @@ val hasil = 6 + 3 * (2.0.pow(3) + Math.sqrt(16.0)) // 42.0 == C++ ```cpp -int hasil = 6 + 3 * (pow(2, 3) + sqrt(16)); // 42 +int hasil = 6 + 3 * (pow(2,3) + sqrt(16)); // 42 ``` == Python ```python import math hasil = 6 + 3 * (pow(2,3) + math.sqrt(16)) # 42.0 ``` +== Rust +```rust +let hasil = 6.0 + 3.0 * (2.0_f64.powf(3.0) + 16.0_f64.sqrt()); // 42.0 +``` ::: -## \ No newline at end of file +## diff --git a/docs/id/arithmetic/percent.md b/docs/id/arithmetic/percent.md new file mode 100644 index 0000000..a9918a5 --- /dev/null +++ b/docs/id/arithmetic/percent.md @@ -0,0 +1,130 @@ +# Persen + +Pernah dapat diskon pas belanja?, biasanya kalo gak di coret ya pake tanda persen ($\%$). Nah, persen ini adalah cara kita mengukur seberapa besar atau kecil suatu nilai dibandingkan dengan nilai aslinya. + +Misalnya kamu beli baju seharga Rp. $100.000$ tapi kamu dapat diskon $20\%$, berarti kamu bisa beli bajunya dengan harga Rp. $80.000$. + +Cara ngitung harga diskon itu gampang banget, kita bisa pakai rumus: +$$ nilai\_diskon = \frac{harga}{100} \times persen $$ + +Jadi kalo kita mau ngitung $20\%$ dari $100.000$ kita bisa tulis: +$$ nilai\_diskon = \frac{100.000}{100} \times 20\% = 20.000 $$ + +karena dibagi $100$ jadi kita bisa kurangi dua nol dari $100.000$ jadi $1.000$ dan dikalikan $20$ jadi $20.000$. + +Kalo diubah ke kodingan, kita bisa tulis seperti ini: +:::tabs key:lang +== Javascript +```js +let harga = 100000; +let diskon = 20; +let nilai_diskon = (harga / 100) * diskon; // 20000 +``` +== Kotlin +```kt +val harga = 100000 +val diskon = 20 +val nilai_diskon = (harga / 100) * diskon // 20000 +``` +== C++ +```cpp +int harga = 100000; +int diskon = 20; +int nilai_diskon = (harga / 100) * diskon; // 20000 +``` +== Python +```python +harga = 100000 +diskon = 20 +nilai_diskon = (harga / 100) * diskon # 20000.0 +``` +== Rust +```rust +let harga = 100000.0; +let diskon = 20.0; +let nilai_diskon = (harga / 100.0) * diskon; // 20000 +``` +::: + +## Mencari Nilai Asli + +Kalo sebelumnya kita ngitung persen dari nilai asli, sekarang kita akan mencari nilai asli dari nilai diskon tersebut. Caranya tinggal dibalik aja rumusnya jadi: +$$ nilai = \frac{nilai_diskon}{diskon} \times 100 $$ + +Misalnya kita punya nilai diskon sebesar $20.000$ dan kita mau cari nilai aslinya, kita bisa tulis: +$$ nilai = \frac{20.000}{20\%} \times 100 = 100.000 $$ + +Kalo diubah ke kodingan, kita bisa tulis seperti ini: +:::tabs key:lang +== Javascript +```js +let nilai_diskon = 20000; +let diskon = 20; +let harga = (nilai_diskon / diskon) * 100; // 100000 +``` +== Kotlin +```kt +val nilai_diskon = 20000 +val diskon = 20 +val harga = (nilai_diskon / diskon) * 100 // 100000 +``` +== C++ +```cpp +int nilai_diskon = 20000; +int diskon = 20; +int harga = (nilai_diskon / diskon) * 100; // 100000 +``` +== Python +```python +nilai_diskon = 20000 +diskon = 20 +harga = (nilai_diskon / diskon) * 100 # 100000.0 +``` +== Rust +```rust +let nilai_diskon = 20000.0; +let diskon = 20.0; +let harga = (nilai_diskon / diskon) * 100.0; // 100000.0 +``` +::: + +## Mencari Persen + +Kalo sebelumnya kita ngitung persen dari nilai asli, sekarang kita akan mencari nilai diskon dari nilai asli tersebut. Rumusnya kita ubah jadi: +$$ persen = \frac{nilai\_diskon}{nilai} \times 100 $$ +Misalnya kita punya nilai asli sebesar $100.000$, dan nilai diskon $20.000$ lalu kita mau cari persennya, kita bisa tulis: +$$ persen = \frac{20.000}{100.000} \times 100 = 20\% $$ + +Kalo diubah ke kodingan, kita bisa tulis seperti ini: +:::tabs key:lang +== Javascript +```js +let harga = 100000; +let nilai_diskon = 20000; +let persen = (nilai_diskon / harga) * 100; // 20 +``` +== Kotlin +```kt +val harga = 100000 +val nilai_diskon = 20000 +val persen = (nilai_diskon / harga) * 100 // 20 +``` +== C++ +```cpp +int harga = 100000; +int nilai_diskon = 20000; +int persen = (nilai_diskon / harga) * 100; // 20 +``` +== Python +```python +harga = 100000 +nilai_diskon = 20000 +persen = (nilai_diskon / harga) * 100 # 20.0 +``` +== Rust +```rust +let harga = 100000.0; +let nilai_diskon = 20000.0; +let persen = (nilai_diskon / harga) * 100.0; // 20.0 +``` +::: diff --git a/docs/id/calculus/limit.md b/docs/id/calculus/limit.md new file mode 100644 index 0000000..928b6f1 --- /dev/null +++ b/docs/id/calculus/limit.md @@ -0,0 +1,295 @@ +# Limit Fungsi + +Limit adalah suatu nilai yang didekati oleh suatu fungsi ketika fungsi diberi input yang juga mendekati suatu nilai tertentu. Limit biasa didefinisikan dengan + +$$\begin{align*} + \lim_{x \to a} f(x) = L +\end{align*}$$ + +Dengan memahami konsep limit, kita bisa dapat mudah untuk mengetahui perilaku sebuah fungsi pada titik-titik tertentu. Kita dapat mengetahui suatu fungsi tersebut apakah bersifat kontinu, tidak kontinu, atau diferensiabel. + +## Cara menentukan limit +Misalnya terdapat sebuah fungsi $f(x) = x+3$ dan kita ingin mengetahui nilai limit disekitar nilai $x=3$. Nilai limit bisa didapat dengan menghitung nilai suatu fungsi dari beberapa nilai input $x$ dari "kanan" dan/atau dari "kiri" + + + +| Kiri | Kanan | +| --------------------|---------------------| +|$f(2.9) = 5.9$ | $f(3.1) = 6.1$ | +|$f(2.99) = 5.99$ | $f(3.01) = 6.01$ | +|$f(2.99) = 5.999$ | $f(3.001) = 6.001$ | +| ... | ... | + +atau dengan menggunakan kode program: +:::tabs key:lang +== Javascript +```js +function f(x){ + return x+3; +} + +function calculateLimit(point){ + //dari kanan + for(let i = 1; i<=10;i++){ + let y = f(point+1/(10**i)); + console.log(`f(${point+1/(10**i)})=${y}`); + } + //dari kiri + for(let i = 1; i<=10;i++){ + let y = f(point-1/(10**i)); + console.log(`f(${point-1/(10**i)})=${y}`); + } +} +calculateLimit(3); + +``` +== Kotlin +```kt +fun f(x: Double): Double { + return x + 3 +} + +fun calculateLimit(point: Double) { + // dari kanan + println("Mencari limit dari arah kanan:") + for (i in 1..10) { + val y = f(point + 1 / Math.pow(10.0, i.toDouble())) + println("f(${point + 1 / Math.pow(10.0, i.toDouble())}) = $y") + } + + // dari kiri + println("Mencari limit dari arah kiri:") + for (i in 1..10) { + val y = f(point - 1 / Math.pow(10.0, i.toDouble())) + println("f(${point - 1 / Math.pow(10.0, i.toDouble())}) = $y") + } +} + +fun main() { + calculateLimit(3.0) +} + +``` +== C++ +```cpp +#include +#include + +double f(double x) { + return x + 3; +} + +void calculateLimit(double point) { + // dari kanan + std::cout << "Mencari limit dari arah kanan:" << std::endl; + for (int i = 1; i <= 10; i++) { + double y = f(point + 1 / std::pow(10, i)); + std::cout << "f(" << (point + 1 / std::pow(10, i)) << ") = " << y << std::endl; + } + + // dri kiri + std::cout << "Mencari limit dari arah kiri:" << std::endl; + for (int i = 1; i <= 10; i++) { + double y = f(point - 1 / std::pow(10, i)); + std::cout << "f(" << (point - 1 / std::pow(10, i)) << ") = " << y << std::endl; + } +} + +int main() { + calculateLimit(3.0); + return 0; +} + +``` +== Python +```python +def f(x): + return x + 3 + +def calculate_limit(point): + # dari kanan + print("Mencari limit dari arah kanan:") + for i in range(1, 11): + y = f(point + 1 / (10 ** i)) + print(f"f({point + 1 / (10 ** i)}) = {y}") + + # dari kiri + print("Mencari limit dari arah kiri:") + for i in range(1, 11): + y = f(point - 1 / (10 ** i)) + print(f"f({point - 1 / (10 ** i)}) = {y}") + +# Run the calculation +calculate_limit(3) +``` +== Rust +```rust +fn f(x: f64) -> f64 { + x + 3.0 +} + +fn calculate_limit(point: f64) { + // Dari kanan + println!("Mencari limit dari arah kanan:"); + for i in 1..=10 { + let y = f(point + 1.0 / 10f64.powi(i)); + println!("f({}) = {}", point + 1.0 / 10f64.powi(i), y); + } + + // Dari kiri + println!("Mencari limit dari arah kiri:"); + for i in 1..=10 { + let y = f(point - 1.0 / 10f64.powi(i)); + println!("f({}) = {}", point - 1.0 / 10f64.powi(i), y); + } +} + +fn main() { + calculate_limit(3.0); +} +``` +::: + +Baik dari kiri maupun kanan, semua nilai fungsi mendekati nilai $6$. Dengan begitu nilai limit dari fungsi disekitar pada $x=3$ adalah $6$. Sekilas hasilnya identik dengan ketika kita langsung memberi input $x=3$ pada fungsi tersebut. Namun terdapat satu keunikan yaitu limit dari suatu fungsi dapat tetap dihitung walaupun fungsi tersebut tidak terdefinisi di titik yang ditentukan. Sebagai contoh, ambil sebuah fungsi yang mirip dengan $f(x)=x+3$, +yakni $g(x)=\frac{x^2-9}{x-3}$ + + + +(coba klik posisi $x=3$) terlihat fungsi tersebut memiliki grafik yang identik dengan $f(x)=x+3$ namun pada nilai $x=3$ fungsi menjadi tidak terdefinisi. Begitupun jika kita hitung nilai limitnya pada titik tersebut +| Kiri | Kanan | +| --------------------|---------------------| +|$f(2.9) = 5.9$ | $f(3.1) = 6.1$ | +|$f(2.99) = 5.99$ | $f(3.01) = 6.01$ | +|$f(2.99) = 5.999$ | $f(3.001) = 6.001$ | +| ... | ... | + +kode program: +:::tabs key:lang +== Javascript +```js +function f(x){ + return (x**2-9)/(x-3); +} + +function calculateLimit(point){ + //dari kanan + for(let i = 1; i<=10;i++){ + let y = f(point+1/(10**i)); + console.log(`f(${point+1/(10**i)})=${y}`); + } + //dari kiri + for(let i = 1; i<=10;i++){ + let y = f(point-1/(10**i)); + console.log(`f(${point-1/(10**i)})=${y}`); + } +} +calculateLimit(3); + +``` +== Kotlin +```kt +fun f(x: Double): Double { + return (x**2-9)/(x-3) +} + +fun calculateLimit(point: Double) { + // dari kanan + println("Mencari limit dari arah kanan:") + for (i in 1..10) { + val y = f(point + 1 / Math.pow(10.0, i.toDouble())) + println("f(${point + 1 / Math.pow(10.0, i.toDouble())}) = $y") + } + + // dari kiri + println("Mencari limit dari arah kiri:") + for (i in 1..10) { + val y = f(point - 1 / Math.pow(10.0, i.toDouble())) + println("f(${point - 1 / Math.pow(10.0, i.toDouble())}) = $y") + } +} + +fun main() { + calculateLimit(3.0) +} + +``` +== C++ +```cpp +#include +#include + +double f(double x) { + return (x**2-9)/(x-3); +} + +void calculateLimit(double point) { + // dari kanan + std::cout << "Mencari limit dari arah kanan:" << std::endl; + for (int i = 1; i <= 10; i++) { + double y = f(point + 1 / std::pow(10, i)); + std::cout << "f(" << (point + 1 / std::pow(10, i)) << ") = " << y << std::endl; + } + + // dri kiri + std::cout << "Mencari limit dari arah kiri:" << std::endl; + for (int i = 1; i <= 10; i++) { + double y = f(point - 1 / std::pow(10, i)); + std::cout << "f(" << (point - 1 / std::pow(10, i)) << ") = " << y << std::endl; + } +} + +int main() { + calculateLimit(3.0); + return 0; +} + +``` +== Python +```python +def f(x): + return (x**2-9)/(x-3) + +def calculate_limit(point): + # dari kanan + print("Mencari limit dari arah kanan:") + for i in range(1, 11): + y = f(point + 1 / (10 ** i)) + print(f"f({point + 1 / (10 ** i)}) = {y}") + + # dari kiri + print("Mencari limit dari arah kiri:") + for i in range(1, 11): + y = f(point - 1 / (10 ** i)) + print(f"f({point - 1 / (10 ** i)}) = {y}") + +# Run the calculation +calculate_limit(3) +``` +== Rust +```rust +fn f(x: f64) -> f64 { + (x.powi(2) - 9.0) / (x - 3.0) +} + +fn calculate_limit(point: f64) { + // Dari kanan + println!("Mencari limit dari arah kanan:"); + for i in 1..=10 { + let y = f(point + 1.0 / 10f64.powi(i)); + println!("f({}) = {}", point + 1.0 / 10f64.powi(i), y); + } + + // Dari kiri + println!("Mencari limit dari arah kiri:"); + for i in 1..=10 { + let y = f(point - 1.0 / 10f64.powi(i)); + println!("f({}) = {}", point - 1.0 / 10f64.powi(i), y); + } +} + +fn main() { + calculate_limit(3.0); +} +``` +::: +dengan begitu kita bisa mengetahui bahwa nilai limit sebenarnya tidak dipengaruhi oleh nilai suatu fungsi pada titik dimana kita menghitung limitnya. diff --git a/docs/guide/index.md b/docs/id/guide/index.md similarity index 87% rename from docs/guide/index.md rename to docs/id/guide/index.md index 64c27c6..93bcaf1 100644 --- a/docs/guide/index.md +++ b/docs/id/guide/index.md @@ -25,16 +25,19 @@ Dalam situs ini, kita akan menggunakan berbagai bahasa pemrograman untuk menjela
Python
+
+ Rust +
Setiap bahasa punya keunikan tersendiri dalam cara mereka menangani matematika. Jadi, siap-siap untuk mengeksplorasi banyak hal baru dalam perjalanan belajar ini! -Di beberapa materi, mungkin bahasa pemrograman yang disebutkan tidak tersedia. +Di beberapa materi, mungkin bahasa pemrograman yang disebutkan tidak tersedia. -Jangan khawatir, kamu tetap bisa mengikuti konsep yang diajarkan dengan bahasa lain yang ada, konsepnya gak jauh beda kok. Intinya, fokus pada implementasinya, ya! +Jangan khawatir, kamu tetap bisa mengikuti konsep yang diajarkan dengan bahasa lain yang ada, konsepnya gak jauh beda kok. Intinya, fokus pada implementasinya, ya! > [!NOTE] -> Di beberapa materi, mungkin bahasa pemrograman yang disebutkan tidak tersedia. +> Di beberapa materi, mungkin bahasa pemrograman yang disebutkan tidak tersedia. > -> Jangan khawatir, kamu tetap bisa mengikuti konsep yang diajarkan dengan bahasa lain yang ada, konsepnya gak jauh beda kok. Intinya, fokus pada implementasinya, ya! \ No newline at end of file +> Jangan khawatir, kamu tetap bisa mengikuti konsep yang diajarkan dengan bahasa lain yang ada, konsepnya gak jauh beda kok. Intinya, fokus pada implementasinya, ya! diff --git a/docs/index.md b/docs/id/index.md similarity index 88% rename from docs/index.md rename to docs/id/index.md index 315512e..9a9b27f 100644 --- a/docs/index.md +++ b/docs/id/index.md @@ -3,12 +3,12 @@ layout: home hero: - name: "Math W Code" + name: "Math With Code" text: "Belajar matematika dengan barisan kode" tagline: Matematika dengan pendekatan yang berbeda image: - src: /icon.png - alt: Math W Code Logo + src: /luca.webp + alt: Luca Math With Code actions: - theme: brand text: Belajar Sekarang @@ -24,7 +24,7 @@ features: linkText: Pelajari - icon: 📐 title: Aljabar - details: Polinomial, Persamaan, Matriks, Determinan dan sebagainya + details: Polinomial, Persamaan, Matriks, Determinan dan sebagainya link: /algebra/function linkText: Pelajari - icon: 📈 @@ -37,6 +37,11 @@ features: details: Data, Distribusi, Regresi, Uji Hipotesis dan sebagainya link: /statistics/measures-concentration-dispersion linkText: Pelajari + - icon: 🔄️ + title: Kalkulus + details: Limit, Turunan, dan Integral + link: /calculus/limit + linkText: Pelajari ---
diff --git a/docs/id/statistics/measures-concentration-dispersion.md b/docs/id/statistics/measures-concentration-dispersion.md new file mode 100644 index 0000000..6c1c0bb --- /dev/null +++ b/docs/id/statistics/measures-concentration-dispersion.md @@ -0,0 +1,836 @@ +# Ukuran Letak + +Ukuran letak merupakan salah satu cabang dari statistika deskriptif, yang mana digunakan untuk mengetahui +letak suatu rangkaian data dalam sebuah distribusi. Ukuran letak dibagi, menjadi 3 yaitu kuartil, desil, dan persentil. +Ukuran letak biasa digunakan dalam kasus distribusi kelompok. + +Misalnya di sebuah posyandu ada petugas yang mengukur berat badan balita untuk memantau perkembangan dan pertumbuhan balita. +Maka ukuran letak digunakan untuk + +| Ukuran Letak | Nilai | Fungsi | +| --------------------- | ------------- | ----------------------------- | +| Persentil | 50 | Acuan rata-rata berat balita | +| Persentil | 5 | Indikasi stunting pada balita | +| Persentil | 85 | Indikasi obesitas pada balita | +| Kuartil | Atas | Acuan batas bawah normal untuk berat badan atau tinggi badan | +| Kuartil | Bawah | Acuan batas atas normal | + +## Persentil + +Persentil diambil dari kata *percent* yang berarti persen. Persentil merupakan pembagian N data yang urut menjadi 100 bagian yang mana data tersebut dibagi sama banyak tersebut, dibatasi oleh 99 nilai persentil. Persentil dibagi menjadi dua menurut jenis datanya, yaitu Data Tunggal dan Data Berkelompok. + +Data tunggal secara umum merupakan deret angka yang terdapat pada sebuah baris atau *array*. Rumus untuk menghitung persentil data tunggal adalah sebagai berikut +$$ Pi = \frac{i(n+1)}{100} $$ + +| Simbol | Pengertian | +| ------------- | ------------- | +| $P_i$ | Persentil ke-i| +| i | Nilai Persentil (1 hingga 99) | +| n | Banyaknya data pada baris atau *array*| + +Berikut ini contoh *case* dari persentil data tunggal dan data berkelompok + +### Data Tunggal +Misalnya ada baris angka seperti dibawah dan kita ingin mencari persentil ke-50 + +:::tabs key:lang +== JavaScript +```javascript +// Data Tunggal +const data_tunggal = [25, 27, 29, 18, 20, 21, 23, 10, 12, 14, 16]; + +const nilai_persen = 100; +const nilai_persentil = 50; //1-99 +const angka_awal = 1; +let hasil_persentil = 0; + +// Mengurutkan data secara ascending +const data_tersortir = data_tunggal.sort((a, b) => a - b); +const jumlah_data = data_tunggal.length; + +// Menghitung posisi persentil +const posisi = (jumlah_data + angka_awal) * (nilai_persentil / nilai_persen); + +// Jika posisi adalah bilangan bulat, ambil nilai pada posisi tersebut +if (Number.isInteger(posisi)) { + hasil_persentil = data_tersortir[posisi - angka_awal]; //20 +} else { + // Jika posisi bukan bilangan bulat, lakukan interpolasi + const indeks_bawah = Math.floor(posisi) - angka_awal; + const indeks_atas = Math.ceil(posisi) - angka_awal; + + // Nilai pada indeks bawah dan atas + const nilai_bawah = data_tersortir[indeks_bawah]; + const nilai_atas = data_tersortir[indeks_atas]; + + // Interpolasi untuk menghitung nilai persentil + hasil_persentil = nilai_bawah + (nilai_atas - nilai_bawah) * (posisi - Math.floor(posisi)); //20 +} +``` + +==Python +```python +# Data Tunggal +data_tunggal = [25, 27, 29, 18, 20, 21, 23, 10, 12, 14, 16] + +nilai_persen = 100 +nilai_persentil = 50 # 1-99 +angka_awal = 1 +hasil_persentil = 0 + +# Mengurutkan data secara ascending +data_tersortir = sorted(data_tunggal) +jumlah_data = len(data_tunggal) + +# Menghitung posisi persentil +posisi = (jumlah_data + angka_awal) * (nilai_persentil / nilai_persen) + +# Jika posisi adalah bilangan bulat, ambil nilai pada posisi tersebut +if posisi.is_integer(): + hasil_persentil = data_tersortir[int(posisi) - angka_awal] # 20 +else: + # Jika posisi bukan bilangan bulat, lakukan interpolasi + indeks_bawah = int(posisi) - angka_awal + indeks_atas = int(posisi + 1) - angka_awal + + # Nilai pada indeks bawah dan atas + nilai_bawah = data_tersortir[indeks_bawah] + nilai_atas = data_tersortir[indeks_bawah] + + # Interpolasi untuk menghitung nilai persentil + hasil_persentil = nilai_bawah + (nilai_atas - nilai_bawah) * (posisi - int(posisi)) # 20 + print(hasil_persentil) +``` +== Rust +```rust +fn main() { + // Data Tunggal + let data_tunggal = vec![25, 27, 29, 18, 20, 21, 23, 10, 12, 14, 16]; + + let nilai_persen = 100.0; + let nilai_persentil = 50.0; // 1-99 + let angka_awal = 1; + let mut hasil_persentil = 0.0; + + // Mengurutkan data secara ascending + let mut data_tersortir = data_tunggal.clone(); + data_tersortir.sort_unstable(); + let jumlah_data = data_tersortir.len(); + + // Menghitung posisi persentil + let posisi = (jumlah_data as f64 + angka_awal as f64) * (nilai_persentil / nilai_persen); + + // Jika posisi adalah bilangan bulat, ambil nilai pada posisi tersebut + if posisi.fract() == 0.0 { + hasil_persentil = data_tersortir[posisi as usize - angka_awal as usize] as f64; + } else { + // Jika posisi bukan bilangan bulat, lakukan interpolasi + let indeks_bawah = posisi.floor() as usize - angka_awal as usize; + let indeks_atas = indeks_bawah + 1; + + // Nilai pada indeks bawah dan atas + let nilai_bawah = data_tersortir[indeks_bawah] as f64; + let nilai_atas = data_tersortir[indeks_atas] as f64; + + // Interpolasi untuk menghitung nilai persentil + hasil_persentil = nilai_bawah + (nilai_atas - nilai_bawah) * (posisi - posisi.floor()); + } + + println!("{}", hasil_persentil); +} +``` +::: + +### Data Berkelompok + +Berikut ini rumus persentil untuk data berkelompok + +$$ P_p = L + \frac{p/100 - \sum f_b}{f_i} \times c $$ + +| Simbol | Pengertian | +| ------------- | --------------------------------------------------------------------- | +| $P_p$ | Nilai persentil ke-i | +| L | Batas bawah kelas interval yang memuat $P_p$ | +| p | Nilai persentil (1 hingga 99) | +| $\sum f_b$ | Jumlah frekuensi kumulatif sebelum kelas interval yang memuat $P_p$ | +| $f_i$ | Frekuensi kelas interval yang memuat $P_p$ | +| c | Panjang kelas interval yang memuat $P_p$ | + +Misalnya ada data kelompok umur warga dibawah 1 tahun hingga 40 tahun seperti dibawah dan kita ingin mencari persentil ke-50 dari kelompok data tersebut +:::tabs key:lang +== JavaScript +```javascript +// Data kelompok +const data_kelompok = [ + { interval: [0, 10], frekuensi: 5 }, + { interval: [10, 20], frekuensi: 10 }, + { interval: [20, 30], frekuensi: 8 }, + { interval: [30, 40], frekuensi: 2 } +]; + +const nilai_persentil = 50; //1-99 +const nilai_awal = 0; +const nilai_persen = 100; +let hasil_persentil = 0; + +// Fungsi untuk menghitung total frekuensi +function hitung_total_frekuensi(data) { + return data.reduce((jumlah, item) => jumlah + item.frekuensi, nilai_awal); +} + +// Fungsi untuk menghitung data kumulatif +function hitung_data_kumulatif(data) { + let frekuensi_kumulatif = 0; + return data.map(item => { + frekuensi_kumulatif += item.frekuensi; + return { ...item, kumulatif: frekuensi_kumulatif }; + }); +} + +// Fungsi untuk menghitung nilai persentil +function hitung_nilai_persentil(data_kelompok, data_kumulatif, persentil) { + const total_frekuensi = hitung_total_frekuensi(data_kelompok); + const posisi = (persentil / nilai_persen) * total_frekuensi; + + const kelas_interval = data_kumulatif.find(item => item.kumulatif >= posisi); + + if (kelas_interval) { + const [batas_bawah, batas_atas] = kelas_interval.interval; + const kumulatif_bawah = data_kumulatif[data_kumulatif.indexOf(kelas_interval) - 1]?.kumulatif || 0; + const frekuensi_dalam_kelas = kelas_interval.frekuensi; + + return batas_bawah + ((posisi - kumulatif_bawah) / frekuensi_dalam_kelas) * (batas_atas - batas_bawah); + } + + return 0; // Atau nilai default yang sesuai jika tidak ditemukan kelas_interval +} + +// Menghitung nilai persentil ke-50 +hasil_persentil = hitung_nilai_persentil(data_kelompok, hitung_data_kumulatif(data_kelompok), nilai_persentil); //17.5 +``` +==Python +```python +# Data kelompok +data_kelompok = [ + {"interval": [0, 10], "frekuensi": 5}, + {"interval": [10, 20], "frekuensi": 10}, + {"interval": [20, 30], "frekuensi": 8}, + {"interval": [30, 40], "frekuensi": 2} +] + +nilai_persentil = 50 # 1-99 +nilai_awal = 0 +nilai_persen = 100 +hasil_persentil = 0 + +# Fungsi untuk menghitung total frekuensi +def hitung_total_frekuensi(data): + return sum(item['frekuensi'] for item in data) + +# Fungsi untuk menghitung data kumulatif +def hitung_data_kumulatif(data): + frekuensi_kumulatif = 0 + hasil = [] + for item in data: + frekuensi_kumulatif += item['frekuensi'] + hasil.append({**item, 'kumulatif': frekuensi_kumulatif}) + return hasil + +# Fungsi untuk menghitung nilai persentil +def hitung_nilai_persentil(data_kelompok, data_kumulatif, persentil): + total_frekuensi = hitung_total_frekuensi(data_kelompok) + posisi = (persentil / nilai_persen) * total_frekuensi + + kelas_interval = next((item for item in data_kumulatif if item['kumulatif'] >= posisi), None) + + if kelas_interval: + batas_bawah, batas_atas = kelas_interval['interval'] + kumulatif_bawah = data_kumulatif[data_kumulatif.index(kelas_interval) - 1]['kumulatif'] if data_kumulatif.index(kelas_interval) > 0 else 0 + frekuensi_dalam_kelas = kelas_interval['frekuensi'] + + return batas_bawah + ((posisi - kumulatif_bawah) / frekuensi_dalam_kelas) * (batas_atas - batas_bawah) + + return 0 # Atau nilai default yang sesuai jika tidak ditemukan kelas_interval + +# Menghitung nilai persentil ke-50 +hasil_persentil = hitung_nilai_persentil(data_kelompok, hitung_data_kumulatif(data_kelompok), nilai_persentil) # 17.5 +print(hasil_persentil) +``` +== Rust +```rust +#[derive(Debug, Clone)] +struct Interval { + batas_bawah: f64, + batas_atas: f64, + frekuensi: usize, +} + +fn hitung_total_frekuensi(data: &[Interval]) -> usize { + data.iter().map(|item| item.frekuensi).sum() +} + +fn hitung_data_kumulatif(data: &[Interval]) -> Vec<(Interval, usize)> { + let mut frekuensi_kumulatif = 0; + data.iter() + .map(|item| { + frekuensi_kumulatif += item.frekuensi; + (item.clone(), frekuensi_kumulatif) + }) + .collect() +} + +fn hitung_nilai_persentil(data_kelompok: &[Interval], data_kumulatif: &[(Interval, usize)], persentil: f64) -> f64 { + let total_frekuensi = hitung_total_frekuensi(data_kelompok); + let posisi = (persentil / 100.0) * total_frekuensi as f64; + + if let Some((kelas_interval, kumulatif_bawah)) = data_kumulatif + .iter() + .find(|(_, kumulatif)| *kumulatif >= posisi as usize) + { + let (batas_bawah, batas_atas) = (kelas_interval.batas_bawah, kelas_interval.batas_atas); + let frekuensi_dalam_kelas = kelas_interval.frekuensi; + + return batas_bawah + ((posisi - *kumulatif_bawah as f64) / frekuensi_dalam_kelas as f64) * (batas_atas - batas_bawah); + } + + 0.0 // Atau nilai default yang sesuai jika tidak ditemukan kelas_interval +} + +fn main() { + let data_kelompok = vec![ + Interval { batas_bawah: 0.0, batas_atas: 10.0, frekuensi: 5 }, + Interval { batas_bawah: 10.0, batas_atas: 20.0, frekuensi: 10 }, + Interval { batas_bawah: 20.0, batas_atas: 30.0, frekuensi: 8 }, + Interval { batas_bawah: 30.0, batas_atas: 40.0, frekuensi: 2 }, + ]; + + let nilai_persentil = 50.0; // 1-99 + let data_kumulatif = hitung_data_kumulatif(&data_kelompok); + + let hasil_persentil = hitung_nilai_persentil(&data_kelompok, &data_kumulatif, nilai_persentil); + println!("{:.1}", hasil_persentil); // Output: 17.5 +} + +``` +::: + +## Desil +Desil merupakan pembagian N data yang urut menjadi 10 bagian yang mana data tersebut dibagi sama banyak tersebut, sehingga terdapat 9 nilai desil. Desil dibagi menjadi dua menurut jenis datanya, yaitu Data Tunggal dan Data Berkelompok. + +Data tunggal secara umum merupakan deret angka yang terdapat pada sebuah baris atau *array*. Rumus untuk menghitung desil data tunggal adalah sebagai berikut +$$ Di = \frac{i(n+1)}{10} $$ + +| Simbol | Pengertian | +| ------------- | ------------------------------------- | +| $D_i$ | Desil ke-i | +| i | Nilai Desil (1 hingga 9) | +| n | Banyaknya data pada baris atau *array*| + +Berikut ini contoh *case* dari desil data tunggal dan data berkelompok (menggunakan data sebelumnya) + +### Data Tunggal +Misalnya ada baris angka seperti dibawah dan kita ingin mencari desil ke-5 + +:::tabs key:lang +== JavaScript +```javascript +// Data Tunggal +const data_tunggal = [25, 27, 29, 18, 20, 21, 23, 10, 12, 14, 16]; + +const nilai_persen = 10 +const nilai_desil = 5; //1-9 +let total_desil = 0; + +// Mengurutkan data secara ascending +const data_tersortir = [...data_tunggal].sort((a, b) => a - b); +const ukuran_data = data_tunggal.length; + +// Menghitung posisi dari nilai desil +const posisi = (nilai_desil * (ukuran_data + 1)) / nilai_persen; + +if (Number.isInteger(posisi)) { + total_desil = data_tersortir[posisi - 1]; //20 +} else { + const indeks_bawah = Math.floor(posisi) - 1; + const indeks_atas = Math.ceil(posisi) - 1; + + const nilai_bawah = data_tersortir[indeks_bawah]; + const nilai_atas = data_tersortir[indeks_atas]; + + // Interpolasi untuk menghitung nilai desil + total_desil = nilai_bawah + (nilai_atas - nilai_bawah) * (posisi - Math.floor(posisi)); //20 +} +``` +==Python +```python +# Data tunggal +data_tunggal = [25, 27, 29, 18, 20, 21, 23, 10, 12, 14, 16] + +nilai_persen = 10 +nilai_desil = 5 # 1-9 +total_desil = 0 + +# Mengurutkan data secara ascending +data_tersortir = sorted(data_tunggal) +ukuran_data = len(data_tunggal) + +# Menghitung posisi dari nilai desil +posisi = (nilai_desil * (ukuran_data + 1)) / nilai_persen + +if posisi.is_integer(): + total_desil = data_tersortir[int(posisi) - 1] # 20 +else: + indeks_bawah = int(posisi) - 1 + indeks_atas = indeks_bawah + 1 + + nilai_bawah = data_tersortir[indeks_bawah] + nilai_atas = data_tersortir[indeks_atas] + + # Interpolasi untuk menghitung nilai desil + total_desil = nilai_bawah + (nilai_atas - nilai_bawah) * (posisi - int(posisi)) # 20 + +print(total_desil) +``` +== Rust +```rust +fn main() { + // Data Tunggal + let data_tunggal = vec![25, 27, 29, 18, 20, 21, 23, 10, 12, 14, 16]; + + let nilai_persen = 10.0; + let nilai_desil = 5; // 1-9 + let mut total_desil = 0.0; + + // Mengurutkan data secara ascending + let mut data_tersortir = data_tunggal.clone(); + data_tersortir.sort_unstable(); + let ukuran_data = data_tunggal.len(); + + // Menghitung posisi dari nilai desil + let posisi = (nilai_desil as f64 * (ukuran_data as f64 + 1.0)) / nilai_persen; + + if posisi.fract() == 0.0 { + total_desil = data_tersortir[posisi as usize - 1] as f64; // Ambil nilai langsung + } else { + let indeks_bawah = posisi.floor() as usize - 1; + let indeks_atas = posisi.ceil() as usize - 1; + + let nilai_bawah = data_tersortir[indeks_bawah] as f64; + let nilai_atas = data_tersortir[indeks_atas] as f64; + + // Interpolasi untuk menghitung nilai desil + total_desil = nilai_bawah + (nilai_atas - nilai_bawah) * (posisi - posisi.floor()); + +``` +::: + +### Data Berkelompok +Berikut ini rumus desil untuk data berkelompok + +$$ D_i = L + \frac{i/10 - \sum f_b}{f_i} \times c $$ + +| Simbol | Pengertian | +| ------------- | --------------------------------------------------------------------- | +| $D_i$ | Nilai desil ke-i | +| L | Batas bawah kelas interval yang memuat $D_i$ | +| i | Nilai desil (1 hingga 9) | +| $\sum f_b$ | Jumlah frekuensi kumulatif sebelum kelas interval yang memuat $D_i$ | +| $f_i$ | Frekuensi kelas interval yang memuat $D_i$ | +| c | Panjang kelas interval yang memuat $D_i$ | + +Misalnya ada data kelompok umur warga dibawah 1 tahun hingga 40 tahun seperti dibawah dan kita ingin mencari desil ke-9 dari kelompok data tersebut +:::tabs key:lang +== JavaScript +```javascript +// Data kelompok +const data_kelompok = [ + { interval: [0, 10], frekuensi: 5 }, + { interval: [10, 20], frekuensi: 10 }, + { interval: [20, 30], frekuensi: 8 }, + { interval: [30, 40], frekuensi: 2 } +]; + +const nilai_desil = 9; // 1-9 untuk desil ke-1 hingga ke-9 +const nilai_awal = 0; +const nilai_persen = 10; +let hasil_desil = 0 + +// Fungsi untuk menghitung total frekuensi +function hitung_total_frekuensi(data) { + return data.reduce((jumlah, item) => jumlah + item.frekuensi, nilai_awal); +} + +// Fungsi untuk menghitung data kumulatif +function hitung_data_kumulatif(data) { + let frekuensi_kumulatif = 0; + return data.map(item => { + frekuensi_kumulatif += item.frekuensi; + return { ...item, kumulatif: frekuensi_kumulatif }; + }); +} + +// Fungsi untuk menghitung nilai desil +function hitung_nilai_desil(data_kelompok, data_kumulatif, desil) { + const total_frekuensi = hitung_total_frekuensi(data_kelompok); + const posisi = (desil / nilai_persen) * total_frekuensi; + + const kelas_interval = data_kumulatif.find(item => item.kumulatif >= posisi); + + if (kelas_interval) { + const [batas_bawah, batas_atas] = kelas_interval.interval; + const kumulatif_bawah = data_kumulatif[data_kumulatif.indexOf(kelas_interval) - 1]?.kumulatif || 0; + const frekuensi_dalam_kelas = kelas_interval.frekuensi; + + return batas_bawah + ((posisi - kumulatif_bawah) / frekuensi_dalam_kelas) * (batas_atas - batas_bawah); + } + + return 0; // Atau nilai default yang sesuai jika tidak ditemukan kelas_interval +} + +// Menghitung nilai desil ke-9 +hasil_desil = hitung_nilai_desil(data_kelompok, hitung_data_kumulatif(data_kelompok), nilai_desil); //29.375 +``` + +==Python + +```python +# Data kelompok +data_kelompok = [ + {"interval": [0, 10], "frekuensi": 5}, + {"interval": [10, 20], "frekuensi": 10}, + {"interval": [20, 30], "frekuensi": 8}, + {"interval": [30, 40], "frekuensi": 2} +] + +nilai_desil = 9 # 1-9 untuk desil ke-1 hingga ke-9 +nilai_awal = 0 +nilai_persen = 10 +hasil_desil = 0 + +# Fungsi untuk menghitung total frekuensi +def hitung_total_frekuensi(data): + return sum(item["frekuensi"] for item in data) + +# Fungsi untuk menghitung data kumulatif +def hitung_data_kumulatif(data): + frekuensi_kumulatif = 0 + hasil = [] + for item in data: + frekuensi_kumulatif += item["frekuensi"] + hasil.append({**item, "kumulatif": frekuensi_kumulatif}) + return hasil + +# Fungsi untuk menghitung nilai desil +def hitung_nilai_desil(data_kelompok, data_kumulatif, desil): + total_frekuensi = hitung_total_frekuensi(data_kelompok) + posisi = (desil / nilai_persen) * total_frekuensi + + kelas_interval = next((item for item in data_kumulatif if item["kumulatif"] >= posisi), None) + + if kelas_interval: + batas_bawah, batas_atas = kelas_interval["interval"] + kumulatif_bawah = data_kumulatif[data_kumulatif.index(kelas_interval) - 1]["kumulatif"] if data_kumulatif.index(kelas_interval) > 0 else 0 + frekuensi_dalam_kelas = kelas_interval["frekuensi"] + + return batas_bawah + ((posisi - kumulatif_bawah) / frekuensi_dalam_kelas) * (batas_atas - batas_bawah) + + return 0 # Atau nilai default yang sesuai jika tidak ditemukan kelas_interval + +# Menghitung nilai desil ke-9 +hasil_desil = hitung_nilai_desil(data_kelompok, hitung_data_kumulatif(data_kelompok), nilai_desil) # 29.375 +print(hasil_desil) +``` +::: + +## Kuartil + +Kuartil merupakan pembagian N data yang urut menjadi 4 bagian yang mana data tersebut dibagi sama banyak tersebut, sehingga terdapat 3 nilai kuartil. Kuartil dibagi menjadi dua menurut jenis datanya, yaitu Data Tunggal dan Data Berkelompok. + +Data tunggal secara umum merupakan deret angka yang terdapat pada sebuah baris atau array. Rumus untuk menghitung kuartil data tunggal adalah sebagai berikut: +$$ Qi = \frac{i(n+1)}{4} $$ + +| Simbol | Pengertian | +| ------------- | ------------------------------------- | +| Qi | Kuartil ke-i | +| i | Nilai Kuartil (1 hingga 9) | +| n | Banyaknya data pada baris atau *array*| + +### Data Tunggal +Misalnya ada baris angka seperti dibawah dan kita ingin mencari kuartil ke-2 + +:::tabs key:lang +== JavaScript +```javascript +// Data Tunggal +const data_tunggal = [25, 27, 29, 18, 20, 21, 23, 10, 12, 14, 16]; + +const nilai_persen = 4; +const nilai_kuartil = 2; // 1-3 +let total_kuartil = 0; + +// Mengurutkan data secara ascending +const data_tersortir = [...data_tunggal].sort((a, b) => a - b); +const jumlah_data = data_tunggal.length; + +// Menghitung posisi dari nilai kuartil +const posisi = (nilai_kuartil * (jumlah_data + 1)) / nilai_persen; + +if (Number.isInteger(posisi)) { + total_kuartil = data_tersortir[posisi - 1]; //20 +} else { + const indeks_bawah = Math.floor(posisi) - 1; + const indeks_atas = Math.ceil(posisi) - 1; + + const nilai_bawah = data_tersortir[indeks_bawah]; + const nilai_atas = data_tersortir[indeks_atas]; + + // Interpolasi untuk menghitung nilai kuartil + total_kuartil = nilai_bawah + (nilai_atas - nilai_bawah) * (posisi - Math.floor(posisi)); //20 +} +``` +::: + +### Data Berkelompok + +Berikut ini rumus kuartil untuk data berkelompok + +$$ Q_i = L + \frac{i/4 - \sum f_b}{f_i} \times c $$ + +| Simbol | Pengertian | +| ------------- | --------------------------------------------------------------------- | +| $Q_i$ | Nilai desil ke-i | +| L | Batas bawah kelas interval yang memuat $Q_i$ | +| i | Nilai desil (1 hingga 9) | +| $\sum f_b$ | Jumlah frekuensi kumulatif sebelum kelas interval yang memuat $Q_i$ | +| $f_i$ | Frekuensi kelas interval yang memuat $Q_i$ | +| c | Panjang kelas interval yang memuat $Q_i$ | + +Misalnya ada data kelompok umur warga dibawah 1 tahun hingga 40 tahun seperti dibawah dan kita ingin mencari kuartil ke-2 dari kelompok data tersebut +:::tabs key:lang +== JavaScript +```javascript +// Data kelompok +const data_kelompok = [ + { interval: [0, 10], frekuensi: 5 }, + { interval: [10, 20], frekuensi: 10 }, + { interval: [20, 30], frekuensi: 8 }, + { interval: [30, 40], frekuensi: 2 } +]; + +const jumlah_persen = 4; +const nilai_kuartil = 2; // 1-3 +const nilai_awal = 0; +let hasil_kuartil = 0 + +// Fungsi untuk menghitung total frekuensi +function hitung_total_frekuensi(data) { + return data.reduce((jumlah, item) => jumlah + item.frekuensi, nilai_awal); +} + +// Fungsi untuk menghitung data kumulatif +function hitung_data_kumulatif(data) { + let frekuensi_kumulatif = 0; + return data.map(item => { + frekuensi_kumulatif += item.frekuensi; + return { ...item, kumulatif: frekuensi_kumulatif }; + }); +} + +// Fungsi untuk menghitung nilai kuartil +function hitung_nilai_kuartil(data_kelompok, data_kumulatif, kuartil) { + const total_frekuensi = hitung_total_frekuensi(data_kelompok); + const posisi = (kuartil / jumlah_persen) * total_frekuensi; + + const kelas_interval = data_kumulatif.find(item => item.kumulatif >= posisi); + + if (kelas_interval) { + const [batas_bawah, batas_atas] = kelas_interval.interval; + const kumulatif_bawah = data_kumulatif[data_kumulatif.indexOf(kelas_interval) - 1]?.kumulatif || 0; + const frekuensi_dalam_kelas = kelas_interval.frekuensi; + + return batas_bawah + ((posisi - kumulatif_bawah) / frekuensi_dalam_kelas) * (batas_atas - batas_bawah); + } + + return 0; // Atau nilai default yang sesuai jika tidak ditemukan kelas_interval +} + +// Menghitung nilai kuartil ke-2 +hasil_kuartil = hitung_nilai_kuartil(data_kelompok, hitung_data_kumulatif(data_kelompok), nilai_kuartil); //17.5 +``` +== Kotlin +```kotlin +// Data kelompok +data class KelompokData(val interval: Pair, val frekuensi: Int) + +val data_kelompok = listOf( + KelompokData(0 to 10, 5), + KelompokData(10 to 20, 10), + KelompokData(20 to 30, 8), + KelompokData(30 to 40, 2) +) + +val nilai_desil = 9 // 1-9 untuk desil ke-1 hingga ke-9 +val nilai_awal = 0 +val nilai_persen = 10 +var hasil_desil = 0.0 + +// Fungsi untuk menghitung total frekuensi +fun hitung_total_frekuensi(data: List): Int { + return data.sumOf { it.frekuensi } +} + +// Fungsi untuk menghitung data kumulatif +fun hitung_data_kumulatif(data: List): List { + var frekuensi_kumulatif = 0 + return data.map { + frekuensi_kumulatif += it.frekuensi + it.copy(frekuensi = frekuensi_kumulatif) + } +} + +// Fungsi untuk menghitung nilai desil +fun hitung_nilai_desil(data_kelompok: List, data_kumulatif: List, desil: Int): Double { + val total_frekuensi = hitung_total_frekuensi(data_kelompok) + val posisi = (desil.toDouble() / nilai_persen) * total_frekuensi + + val kelas_interval = data_kumulatif.find { it.frekuensi >= posisi } + + kelas_interval?.let { + val (batas_bawah, batas_atas) = it.interval + val kumulatif_bawah = data_kumulatif.getOrNull(data_kumulatif.indexOf(it) - 1)?.frekuensi ?: 0 + val frekuensi_dalam_kelas = it.frekuensi - kumulatif_bawah + + return batas_bawah + ((posisi - kumulatif_bawah) / frekuensi_dalam_kelas) * (batas_atas - batas_bawah) + } + + return 0.0 // Atau nilai default yang sesuai jika tidak ditemukan kelas_interval +} + +// Menghitung nilai desil ke-9 +hasil_desil = hitung_nilai_desil(data_kelompok, hitung_data_kumulatif(data_kelompok), nilai_desil) +println(hasil_desil) // Output: 29.375 +``` +== C++ +```cpp +#include +#include +#include // untuk std::accumulate + +struct KelompokData { + std::pair interval; + int frekuensi; +}; + +int nilai_desil = 9; // 1-9 untuk desil ke-1 hingga ke-9 +int nilai_awal = 0; +int nilai_persen = 10; +double hasil_desil = 0; + +// Fungsi untuk menghitung total frekuensi +int hitung_total_frekuensi(const std::vector& data) { + return std::accumulate(data.begin(), data.end(), nilai_awal, + [](int jumlah, const KelompokData& item) { + return jumlah + item.frekuensi; + }); +} + +// Fungsi untuk menghitung data kumulatif +std::vector hitung_data_kumulatif(const std::vector& data) { + int frekuensi_kumulatif = 0; + std::vector data_kumulatif; + + for (const auto& item : data) { + frekuensi_kumulatif += item.frekuensi; + data_kumulatif.push_back({ item.interval, frekuensi_kumulatif }); + } + + return data_kumulatif; +} + +// Fungsi untuk menghitung nilai desil +double hitung_nilai_desil(const std::vector& data_kelompok, const std::vector& data_kumulatif, int desil) { + int total_frekuensi = hitung_total_frekuensi(data_kelompok); + double posisi = (static_cast(desil) / nilai_persen) * total_frekuensi; + + auto kelas_interval = std::find_if(data_kumulatif.begin(), data_kumulatif.end(), + [posisi](const KelompokData& item) { + return item.frekuensi >= posisi; + }); + + if (kelas_interval != data_kumulatif.end()) { + int batas_bawah = kelas_interval->interval.first; + int batas_atas = kelas_interval->interval.second; + int index = std::distance(data_kumulatif.begin(), kelas_interval); + int kumulatif_bawah = (index > 0) ? data_kumulatif[index - 1].frekuensi : 0; + int frekuensi_dalam_kelas = kelas_interval->frekuensi - kumulatif_bawah; + + return batas_bawah + ((posisi - kumulatif_bawah) / frekuensi_dalam_kelas) * (batas_atas - batas_bawah); + } + + return 0.0; // Atau nilai default yang sesuai jika tidak ditemukan kelas_interval +} + +int main() { + std::vector data_kelompok = { + {{0, 10}, 5}, + {{10, 20}, 10}, + {{20, 30}, 8}, + {{30, 40}, 2} + }; + + // Menghitung nilai desil ke-9 + hasil_desil = hitung_nilai_desil(data_kelompok, hitung_data_kumulatif(data_kelompok), nilai_desil); + std::cout << hasil_desil << std::endl; // Output: 29.375 + + return 0; +} +``` +==Python +```python +# Data kelompok +data_kelompok = [ + {"interval": [0, 10], "frekuensi": 5}, + {"interval": [10, 20], "frekuensi": 10}, + {"interval": [20, 30], "frekuensi": 8}, + {"interval": [30, 40], "frekuensi": 2} +] + +jumlah_persen = 4 +nilai_kuartil = 2 # 1-3 +nilai_awal = 0 +hasil_kuartil = 0 + +# Fungsi untuk menghitung total frekuensi +def hitung_total_frekuensi(data): + return sum(item["frekuensi"] for item in data) + +# Fungsi untuk menghitung data kumulatif +def hitung_data_kumulatif(data): + frekuensi_kumulatif = 0 + hasil = [] + for item in data: + frekuensi_kumulatif += item["frekuensi"] + hasil.append({**item, "kumulatif": frekuensi_kumulatif}) + return hasil + +# Fungsi untuk menghitung nilai kuartil +def hitung_nilai_kuartil(data_kelompok, data_kumulatif, kuartil): + total_frekuensi = hitung_total_frekuensi(data_kelompok) + posisi = (kuartil / jumlah_persen) * total_frekuensi + + kelas_interval = next((item for item in data_kumulatif if item["kumulatif"] >= posisi), None) + + if kelas_interval: + batas_bawah, batas_atas = kelas_interval["interval"] + kumulatif_bawah = data_kumulatif[data_kumulatif.index(kelas_interval) - 1]["kumulatif"] if data_kumulatif.index(kelas_interval) > 0 else 0 + frekuensi_dalam_kelas = kelas_interval["frekuensi"] + + return batas_bawah + ((posisi - kumulatif_bawah) / frekuensi_dalam_kelas) * (batas_atas - batas_bawah) + + return 0 # Atau nilai default yang sesuai jika tidak ditemukan kelas_interval + +# Menghitung nilai kuartil ke-2 +hasil_kuartil = hitung_nilai_kuartil(data_kelompok, hitung_data_kumulatif(data_kelompok), nilai_kuartil) # 17.5 +print(hasil_kuartil) +``` +::: diff --git a/docs/id/statistics/simple-linear-regression.md b/docs/id/statistics/simple-linear-regression.md new file mode 100644 index 0000000..ffdc90d --- /dev/null +++ b/docs/id/statistics/simple-linear-regression.md @@ -0,0 +1,365 @@ +--- +contributors: + - name: "Fadjar" + username: "fadjarrafi" +--- + +# Regresi Linier Sederhana + +Pernahkah kamu bertanya-tanya bagaimana perusahaan besar mengambil keputusan investasi iklan mereka? Atau bagaimana properti menentukan harga jual rumah? Jawabannya ada pada teknik statistik yang disebut regresi linier sederhana. + +Regresi linier sederhana adalah metode statistik yang memungkinkan kita memahami dan memprediksi hubungan antara dua variabel. Bayangkan seperti mencari "benang merah" yang menghubungkan biaya iklan ($x$) dengan tingkat penjualan ($y$). + +Secara matematis, hubungan ini dapat dinyatakan dengan rumus: + +$$ +y = \beta_0 + \beta_1 x + \varepsilon +$$ + +Dimana: + +| Simbol | Pengertian | +| ------------- | ------------- | +| $x$ | Variabel Independen | +| $y$ | Variabel Dependen| +| β₀ | *Intercept* (nilai $y$ ketika $x$ = 0)| +| β₁ | *Slope* (seberapa besar perubahan $y$ untuk setiap unit perubahan $x$)| +| ε | *Error term*| + +## Fungsi Regresi Linier + +Regresi linier memiliki dua peran krusial dalam analisis data: + +1. **Pembuktian Hubungan** + - Membuktikan secara statistik apakah ada hubungan nyata antara dua variable. + - Mengukur seberapa kuat hubungan tersebut. + - Contoh: Apakah benar tingkat pendidikan mempengaruhi tingkat pendapatan? + +2. **Kekuatan Prediksi** + - Memungkinkan kita memprediksi nilai di masa depan + - Membuat keputusan bisnis berdasarkan data historis + - Contoh: JIka kita menaikkan anggaran iklan sebesar $x$, berapa peningkatan penjualan ($y$) yang bisa diharapkan? + +## Menghitung Regresi Linier + +Mari kita ambil kasus dimana kita ingin mengetahui keterkaitan antara biaya iklan ($x$) dan penjualan ($y$). Sebagai contoh kita memiliki data seperti berikut: + +| Biaya Iklan | Unit | +| ------------ | ------------- | +| 100 | 500 | +| 200 | 700 | +| 300 | 900 | +| 400 | 1100 | +| 500 | 1300 | + +Sebelum kita menghitung regresi linier sederhana dengan data tersebut, kita perlu: + +1. Menghitung *Slope* $\beta_1$ +2. Menghitung *Intercept* $\beta_0$ + +### Menghitung *Slope* ($\beta_1$) + +*Slope* atau kemiringan menggambarkan perubahan variabel $y$ terhadap setiap perubahan variabel $x$. Kita bisa menghitung *slope* menggunakan rumus sebagai berikut: + +$$ +\beta_1 = \frac{\sum(x_i - \bar{x})(y_i - \bar{y})}{\sum(x_i - \bar{x})^2} +$$ + +Dimana: + +| Simbol | Pengertian | +| ----------------- | ------------- | +| $x_i$ | Nilai individual dari variabel Independen | +| $y_i$ | Nilai individual dari variabel Dependen | +| $\bar{x}$ | Rata-rata nilai dari seluruh variabel Independen | +| $\bar{y}$ | Rata-rata nilai dari seluruh variabel Dependen | + +Mari kita hitung terlebih dahulu rata-rata dari tiap biaya iklan (X) dan unit penjualan (Y): + +$$ \bar{x} = (100 + 200 + 300 + 400 + 500) / 5 = 300 $$ + +$$ \bar{y} = (500 + 700 + 900 + 1100 + 1300) / 5 = 900 $$ + +Setelah kita menemukan rata-rata dari biaya iklan dan unit penjualan, selanjutnya kita hitung *Slope* nya: + +$$ (100 - 300)(500 - 900) = (-200)(-400) = 80,000 $$ +$$ (200 - 300)(700 - 900) = (-100)(-200) = 20,000 $$ +$$ (300 - 300)(900 - 900) = (0)(0) = 0 $$ +$$ (400 - 300)(1100 - 900) = (100)(200) = 20,000 $$ +$$ (500 - 300)(1300 - 900) = (200)(400) = 80,000 $$ +$$ Total = 200,000 $$ + +$$ (100 - 300)² = (-200)² = 40,000 $$ +$$ (200 - 300)² = (-100)² = 10,000 $$ +$$ (300 - 300)² = (0)² = 0 $$ +$$ (400 - 300)² = (100)² = 10,000 $$ +$$ (500 - 300)² = (200)² = 40,000 $$ +$$ Total = 100,000 $$ + +$$ \beta_1 = 200,000/100,000 = 2 $$ + +Dari penjualan data diatas, kita mendapatkan nilai dari *Slope* = 2 yang berarti bahwa setiap kenaikan 1 unit biaya ($x$), akan meningkatkan penjualan ($y$) sebesar 2 unit. + +### Menghitung *Intercept* ($\beta_0$) + +Setelah kita menemukan nilai *Slope*, kita hitung nilai *Intercept* dengan rumus berikut: + +$$ +\beta_0 = \bar{y} - \beta_1\bar{x} +$$ + +Dimana: + +| Simbol | Pengertian | +| ----------------- | ------------- | +| $\bar{y}$ | Rata-rata nilai dari seluruh variabel independen | +| $\bar{x}$ | Rata-rata nilai dari seluruh variabel dependen | +| $\beta_1$ | *Slope* | + +Mari kita hitung *Intercept* dari *Slope* yang sudah kita hitung sebelumnya: + +$$ \beta_0 = 900 - (2 × 300) $$ + +$$ \beta_0 = 300 $$ + +Ini berarti ketika biaya iklan 0, prediksi penjualan adalah 300 unit. Setelah kita mengetahui *Slope* dan *intercept*, maka kita bisa masukkan ke dalam persamaan regresi linier sebagai berikut: + +$$ y = 300 + 2x $$ + +Lalu bagaimana kita menggunakan rumus ini untuk membuat prediksi? sebagai contoh, di iklan berikutnya kita ingin mengetahu seberapa banyak penjualan jika kita mengeluarkan biaya iklan sejumlah 250. Kita masukkan biaya iklan sejumlah 250 kedalam persamaan yang sudah kita tentukan: + +$$ y = 300 + 2(250) $$ +$$ y = 300 + 500 $$ +$$ y = 800 $$ + +Jadi jika kita mengeluarkan biaya iklan sejumlah 250, maka dapat diprediksi tingkat penjualan sejumlah 800 unit. Beikut persamaan yang telah kita dapatkan jika kita gambar dalam grafik: + + + +Perhitungan regresi linier yang telah kita buat dapat kita simulasikan dalam program sebagai berikut: + +:::tabs +== JavaScript +```js +// Data penjualan dan iklan +const data_penjualan = { + biaya_iklan: [100, 200, 300, 400, 500], + unit_terjual: [500, 700, 900, 1100, 1300] +}; + +// Menghitung rata-rata dari array +function hitung_rata_rata(data) { + return data.reduce((total, nilai) => total + nilai, 0) / data.length; +} + +// Menghitung slope (β₁) dari data +function hitung_slope(data) { + const rata_x = hitung_rata_rata(data.biaya_iklan); + const rata_y = hitung_rata_rata(data.unit_terjual); + + let pembilang = 0; + let penyebut = 0; + + // Hitung pembilang dan penyebut untuk rumus slope + for (let i = 0; i < data.biaya_iklan.length; i++) { + const selisih_x = data.biaya_iklan[i] - rata_x; + const selisih_y = data.unit_terjual[i] - rata_y; + + pembilang += selisih_x * selisih_y; + penyebut += selisih_x * selisih_x; + } + + return pembilang / penyebut; +} + +// Menghitung intercept (β₀) dari data +function hitung_intercept(data, slope) { + const rata_x = hitung_rata_rata(data.biaya_iklan); + const rata_y = hitung_rata_rata(data.unit_terjual); + + return rata_y - (slope * rata_x); +} + +// Memprediksi unit terjual berdasarkan biaya iklan +function prediksi_penjualan(biaya_iklan, slope, intercept) { + return intercept + (slope * biaya_iklan); +} + +// Hitung regresi +const slope = hitung_slope(data_penjualan); +const intercept = hitung_intercept(data_penjualan, slope); + +// Tampilkan hasil +console.log(`Slope (β₁): ${slope}`); // output: 2 +console.log(`Intercept (β₀): ${intercept}`); // output: 300 + +// Contoh prediksi +const biaya_baru = 250; +const prediksi = prediksi_penjualan(biaya_baru, slope, intercept); +console.log(`${prediksi} unit`); +``` +::: +## Asumsi Klasik Regresi Linier + +Sebelum mulai menerapkan regresi linier, penting untuk kita memahami asumsi-asumsi dasarnya: + +1. **Linearitas** + +Asumsi pertama dan yang paling mendasar adalah hubungan antara variabel independen ($x$) dan variabel dependen ($y$) harus bersifat linier. Bayangkan jika kita menggambar titik-titik data dalam sebuah grafik, maka titik-titik tersebut seharusnya membentuk pola yang bisa didekati dengan garis lurus. Kita bisa memeriksa asumsi ini dengan membuat scatter plot dari data kita. Jika pola yang terbentuk jauh dari linier, misalnya membentuk kurva atau pola lainnya, maka kita perlu melakukan transformasi data terlebih dahulu. Transformasi yang umum dilakukan bisa berupa logaritma, akar kuadrat, atau transformasi lainnya yang sesuai dengan bentuk data. + +2. **Independensi** + +Asumsi kedua adalah setiap pengamatan dalam data kita harus bersifat independen atau tidak saling mempengaruhi satu sama lain. Hal ini sangat penting terutama ketika kita bekerja dengan data yang dikumpulkan dari waktu ke waktu (time series). Sebagai contoh, jika kita menganalisis penjualan harian, maka penjualan hari ini seharusnya tidak dipengaruhi oleh penjualan kemarin. Jika terdapat pengaruh antar pengamatan (autokorelasi), hasil analisis kita bisa menjadi bias. Kita bisa memeriksa asumsi ini dengan plot ACF (Autocorrelation Function) atau menggunakan uji statistik seperti Durbin-Watson. + +3. **Homoskedastisitas** + +Istilah yang mungkin terdengar rumit ini sebenarnya merujuk pada konsep yang cukup sederhana: varians dari error (residual) harus bersifat konstan untuk semua nilai variabel independen. Dalam konteks contoh kita tentang iklan dan penjualan, ini berarti tingkat kesalahan prediksi seharusnya relatif sama, baik untuk biaya iklan yang rendah maupun tinggi. Kita bisa memeriksa asumsi ini dengan membuat plot antara residual dan nilai prediksi. Jika plot menunjukkan pola tertentu (misalnya membentuk corong), maka asumsi ini tidak terpenuhi dan kita perlu melakukan transformasi data atau menggunakan metode analisis yang lebih robust. + +4. **Normalitas** + +Asumsi terakhir adalah residual atau error harus mengikuti distribusi normal. Ini penting terutama ketika kita ingin melakukan uji hipotesis atau membuat interval kepercayaan. Bayangkan jika kita membuat histogram dari error, maka bentuknya harus menyerupai lonceng yang simetris (kurva normal). Kita bisa memeriksa asumsi ini dengan beberapa cara, mulai dari yang sederhana seperti membuat histogram residual atau Q-Q plot, hingga uji formal seperti Shapiro-Wilk atau Kolmogorov-Smirnov. + + +## Uji Persamaan dengan Koefisien Determinasi ($R^2$) + +Lalu bagaimana jika kita ingin mengetahui kemampuan persamaan regresi dalam menerangkan seberapa pengruh variabel independen secara bersama-sama (stimultan) mempengaruhi variabel dependen? disinilah kita melakukan Uji Koefisien Determinasi. Koefisien determinasi adalah ukuran yang menunjukkan seberapa baik model regresi menjelaskan data. Kita bisa menghitung koefisien determinasi dengan rumus: + +$$ R^2 = 1 - \frac{\sum(y_i - \hat{y_i})^2}{\sum(y_i - \bar{y})^2} $$ + +Dimana: + +| Simbol | Pengertian | +| ----------------- | ------------- | +| $y_i$ | Nilai Aktual | +| $\hat{y_i}$ | Nilai Prediksi | +| $\bar{y}$ | Rata-Rata Nilai Aktual | + +Koefisien determinasi menggambarkan besarnya keragaman (informasi) di dalam variabel $y$ yang dapat diberikan oleh model regresi yang kita didapatkan. Nilai koefisien berkisan antara 0 sampai 1. Jika nilai $R^2$ dikalikan 100%, maka ini menunjukkan persentasi keragaman (informasi) dalam variabel $y$. + +Untuk dapat menghitung $R^2$, kita perlu untuk menghitung: + +1. Nilai Prediksi ($\hat{y_i}$) untuk Setiap $x$ +2. Nilai Rata-Rata $y$ Aktual ($\bar{y}$) +3. Nilai SS_total dan SS_residual + +### Menghitung Nilai Prediksi ($\hat{y_i}$) untuk Setiap $x$ + +Kita hitung setiap nilai yang kita miliki dengan persamaan regresi linier yang sudah kita dapatkan sebelumnya, yaitu: $y = 300 + 2x$ + +| Biaya Iklan (X) | Unit (Y) | $\bar{y}$ (Y Prediksi) | +| ---------------- | ------------- | ---------------------- | +| 100 | 500 | 300 + 2(100) = 500 | +| 200 | 700 | 300 + 2(200) = 700 | +| 300 | 900 | 300 + 2(300) = 900 | +| 400 | 1100 | 300 + 2(400) = 1100 | +| 500 | 1300 | 300 + 2(500) = 1300 | + +### Menghitung Nilai Rata-Rata $y$ Aktual ($\bar{y}$) + +$$ \bar{y} = (500 + 700 + 900 + 1100 + 1300) / 5 = 900 $$ + +$$ (500 - 900)² = (-400)² = 160,000 $$ +$$ (700 - 900)² = (-200)² = 40,000 $$ +$$ (900 - 900)² = 0 $$ +$$ (1100 - 900)² = (200)² = 40,000 $$ +$$ (1300 - 900)² = (400)² = 160,000 $$ +$$ SStotal = 400,000 $$ + +### Menghitung $R^2$ + +Kita bisa menghitung $R^2$ dengan menggunakan rumus: + +$$ R^2 = 1 - (SSresidual / SStotal) $$ + +Dimana: + +| Simbol | Pengertian | +| ----------------- | ------------- | +| $SSresidual$ | jumlah kuadrat akibat regresi | +| $SStotal$ | total kuadrat | + +mari kita hitung total $SStotal$ dan $SSresidual$ sebagai berikut: +$$ SStotal = \sum(y - \bar{y})^2 $$ + +$$ (500 - 500)² = 0 $$ +$$ (700 - 700)² = 0 $$ +$$ (900 - 900)² = 0 $$ +$$ (1100 - 1100)² = 0 $$ +$$ (1300 - 1300)² = 0 $$ + +$$ SSresidual = 0 $$ + +Setelah kita mendapatkan nilai dari $SStotal$ dan $SSresidual$, kita masukkan kedalam rumus koefisien determinasi: + +$$ R^2 = 1 - (0 / 400,000) $$ +$$ R^2 = 1 $$ + +Hasil $R^2$ = 1 menunjukkan bahwa: + +1. Model menjelaskan 100% variasi dalam data +2. Semua titik data tepat berada pada garis regresi +3. Prediksi model sempurna untuk data yang ada + +Berikut perhitungan $R^2$ jika kita gambarkan melalui grafik: + + + + + + + + + + + + + + + + + Biaya Iklan (X) + Penjualan (Y) + + + + + + + + + + + + + R² = 1.0 + Perfect Fit + + +Ini menunjukkan bahwa bahkan dengan sedikit variasi dalam data, $R^2$ tetap bisa sangat tinggi jika model cocok dengan pola data. Kita dapat mensimulasikan perhitungan koefisien determinasi dengan program segabai berikut: + +:::tabs +== JavaScript +```js +// Menghitung koefisien determinasi (R²) +function hitung_r_squared(data, slope, intercept) { + const rata_y = hitung_rata_rata(data.unit_terjual); + + let ss_total = 0; // Sum of squares total + let ss_residual = 0; // Sum of squares residual + + for (let i = 0; i < data.biaya_iklan.length; i++) { + const y_prediksi = intercept + (slope * data.biaya_iklan[i]); + const y_aktual = data.unit_terjual[i]; + + ss_total += Math.pow(y_aktual - rata_y, 2); + ss_residual += Math.pow(y_aktual - y_prediksi, 2); + } + + return 1 - (ss_residual / ss_total); +} + +// Penggunaan +const r_squared = hitung_r_squared(data_penjualan, slope, intercept); +console.log(`R² (Koefisien Determinasi): ${r_squared.toFixed(4)}`); // Output 0.9989 yang kita bulatkan menjadi 1 +``` +::: diff --git a/docs/public/icon.png b/docs/public/icon.png deleted file mode 100644 index 2e3b78f..0000000 Binary files a/docs/public/icon.png and /dev/null differ diff --git a/docs/public/img/sponsors/imphnen.png b/docs/public/img/sponsors/imphnen.png index 3607597..ef8388e 100644 Binary files a/docs/public/img/sponsors/imphnen.png and b/docs/public/img/sponsors/imphnen.png differ diff --git a/docs/public/img/sponsors/jamcoder.jpg b/docs/public/img/sponsors/jamcoder.jpg index b2d8e8b..fb21cc6 100644 Binary files a/docs/public/img/sponsors/jamcoder.jpg and b/docs/public/img/sponsors/jamcoder.jpg differ diff --git a/docs/public/luca.webp b/docs/public/luca.webp new file mode 100644 index 0000000..5273965 Binary files /dev/null and b/docs/public/luca.webp differ diff --git a/docs/statistics/measures-concentration-dispersion.md b/docs/statistics/measures-concentration-dispersion.md deleted file mode 100644 index 18b8080..0000000 --- a/docs/statistics/measures-concentration-dispersion.md +++ /dev/null @@ -1,713 +0,0 @@ -# Ukuran Letak - -Ukuran letak merupakan salah satu cabang dari statistika deskriptif, yang mana digunakan untuk mengetahui -letak suatu rangkaian data dalam sebuah distribusi. Ukuran letak dibagi, menjadi 3 yaitu kuartil, desil, dan persentil. -Ukuran letak biasa digunakan dalam kasus distribusi kelompok. - -Misalnya di sebuah posyandu ada petugas yang mengukur berat badan balita untuk memantau perkembangan dan pertumbuhan balita. -Maka ukuran letak digunakan untuk - -| Ukuran Letak | Nilai | Fungsi | -| --------------------- | ------------- | ----------------------------- | -| Persentil | 50 | Acuan rata-rata berat balita | -| Persentil | 5 | Indikasi stunting pada balita | -| Persentil | 85 | Indikasi obesitas pada balita | -| Kuartil | Atas | Acuan batas bawah normal untuk berat badan atau tinggi badan | -| Kuartil | Bawah | Acuan batas atas normal | - -## Persentil - -Persentil diambil dari kata *percent* yang berarti persen. Persentil merupakan pembagian N data yang urut menjadi 100 bagian yang mana data tersebut dibagi sama banyak tersebut, dibatasi oleh 99 nilai persentil. Persentil dibagi menjadi dua menurut jenis datanya, yaitu Data Tunggal dan Data Berkelompok. - -Data tunggal secara umum merupakan deret angka yang terdapat pada sebuah baris atau *array*. Rumus untuk menghitung persentil data tunggal adalah sebagai berikut -$$ Pi = \frac{i(n+1)}{100} $$ - -| Simbol | Pengertian | -| ------------- | ------------- | -| $P_i$ | Persentil ke-i| -| i | Nilai Persentil (1 hingga 99) | -| n | Banyaknya data pada baris atau *array*| - -Berikut ini contoh *case* dari persentil data tunggal dan data berkelompok - -### Data Tunggal -Misalnya ada baris angka seperti dibawah dan kita ingin mencari persentil ke-50 - -:::tabs -== JavaScript -```javascript -// Data Tunggal -const dataTunggal = [25, 27, 29, 18, 20, 21, 23, 10, 12, 14, 16]; - -const nilaiPersen = 100; -const nilaiPersentil = 50; //1-99 -const angkaAwal = 1; -let hasilPersentil = 0; - -// Mengurutkan data secara ascending -const dataTersortir = dataTunggal.sort((a, b) => a - b); -const jumlahData = dataTunggal.length; - -// Menghitung posisi persentil -const posisi = (jumlahData + angkaAwal) * (nilaiPersentil / nilaiPersen); - -// Jika posisi adalah bilangan bulat, ambil nilai pada posisi tersebut -if (Number.isInteger(posisi)) { - hasilPersentil = dataTersortir[posisi - angkaAwal]; //20 -} else { - // Jika posisi bukan bilangan bulat, lakukan interpolasi - const indeksBawah = Math.floor(posisi) - angkaAwal; - const indeksAtas = Math.ceil(posisi) - angkaAwal; - - // Nilai pada indeks bawah dan atas - const nilaiBawah = dataTersortir[indeksBawah]; - const nilaiAtas = dataTersortir[indeksAtas]; - - // Interpolasi untuk menghitung nilai persentil - hasilPersentil = nilaiBawah + (nilaiAtas - nilaiBawah) * (posisi - Math.floor(posisi)); //20 -} -``` - -==Python -```python -# Data Tunggal -dataTunggal = [25, 27, 29, 18, 20, 21, 23, 10, 12, 14, 16] - -nilaiPersen = 100 -nilaiPersentil = 50 # 1-99 -angkaAwal = 1 -hasilPersentil = 0 - -# Mengurutkan data secara ascending -dataTersortir = sorted(dataTunggal) -jumlahData = len(dataTunggal) - -# Menghitung posisi persentil -posisi = (jumlahData + angkaAwal) * (nilaiPersentil / nilaiPersen) - -# Jika posisi adalah bilangan bulat, ambil nilai pada posisi tersebut -if posisi.is_integer(): - hasilPersentil = dataTersortir[int(posisi) - angkaAwal] # 20 -else: - # Jika posisi bukan bilangan bulat, lakukan interpolasi - indeksBawah = int(posisi) - angkaAwal - indeksAtas = int(posisi + 1) - angkaAwal - - # Nilai pada indeks bawah dan atas - nilaiBawah = dataTersortir[indeksBawah] - nilaiAtas = dataTersortir[indeksBawah] - - # Interpolasi untuk menghitung nilai persentil - hasilPersentil = nilaiBawah + (nilaiAtas - nilaiBawah) * (posisi - int(posisi)) # 20 - print(hasilPersentil) -``` -::: - -### Data Berkelompok - -Berikut ini rumus persentil untuk data berkelompok - -$$ P_p = L + \frac{p/100 - \sum f_b}{f_i} \times c $$ - -| Simbol | Pengertian | -| ------------- | --------------------------------------------------------------------- | -| $P_p$ | Nilai persentil ke-i | -| L | Batas bawah kelas interval yang memuat $P_p$ | -| p | Nilai persentil (1 hingga 99) | -| $\sum f_b$ | Jumlah frekuensi kumulatif sebelum kelas interval yang memuat $P_p$ | -| $f_i$ | Frekuensi kelas interval yang memuat $P_p$ | -| c | Panjang kelas interval yang memuat $P_p$ | - -Misalnya ada data kelompok umur warga dibawah 1 tahun hingga 40 tahun seperti dibawah dan kita ingin mencari persentil ke-50 dari kelompok data tersebut -:::tabs -== JavaScript -```javascript -// Data kelompok -const dataKelompok = [ - { interval: [0, 10], frekuensi: 5 }, - { interval: [10, 20], frekuensi: 10 }, - { interval: [20, 30], frekuensi: 8 }, - { interval: [30, 40], frekuensi: 2 } -]; - -const nilaiPersentil = 50; //1-99 -const nilaiAwal = 0; -const nilaiPersen = 100; -let hasilPersentil = 0; - -// Fungsi untuk menghitung total frekuensi -function hitungTotalFrekuensi(data) { - return data.reduce((jumlah, item) => jumlah + item.frekuensi, nilaiAwal); -} - -// Fungsi untuk menghitung data kumulatif -function hitungDataKumulatif(data) { - let frekuensiKumulatif = 0; - return data.map(item => { - frekuensiKumulatif += item.frekuensi; - return { ...item, kumulatif: frekuensiKumulatif }; - }); -} - -// Fungsi untuk menghitung nilai persentil -function hitungNilaiPersentil(dataKelompok, dataKumulatif, persentil) { - const totalFrekuensi = hitungTotalFrekuensi(dataKelompok); - const posisi = (persentil / nilaiPersen) * totalFrekuensi; - - const kelasInterval = dataKumulatif.find(item => item.kumulatif >= posisi); - - if (kelasInterval) { - const [batasBawah, batasAtas] = kelasInterval.interval; - const kumulatifBawah = dataKumulatif[dataKumulatif.indexOf(kelasInterval) - 1]?.kumulatif || 0; - const frekuensiDalamKelas = kelasInterval.frekuensi; - - return batasBawah + ((posisi - kumulatifBawah) / frekuensiDalamKelas) * (batasAtas - batasBawah); - } - - return 0; // Atau nilai default yang sesuai jika tidak ditemukan kelasInterval -} - -// Menghitung nilai persentil ke-50 -hasilPersentil = hitungNilaiPersentil(dataKelompok, hitungDataKumulatif(dataKelompok), nilaiPersentil); //17.5 -``` -==Python -```python -# Data kelompok -dataKelompok = [ - {"interval": [0, 10], "frekuensi": 5}, - {"interval": [10, 20], "frekuensi": 10}, - {"interval": [20, 30], "frekuensi": 8}, - {"interval": [30, 40], "frekuensi": 2} -] - -nilaiPersentil = 50 # 1-99 -nilaiAwal = 0 -nilaiPersen = 100 -hasilPersentil = 0 - -# Fungsi untuk menghitung total frekuensi -def hitungTotalFrekuensi(data): - return sum(item['frekuensi'] for item in data) - -# Fungsi untuk menghitung data kumulatif -def hitungDataKumulatif(data): - frekuensiKumulatif = 0 - hasil = [] - for item in data: - frekuensiKumulatif += item['frekuensi'] - hasil.append({**item, 'kumulatif': frekuensiKumulatif}) - return hasil - -# Fungsi untuk menghitung nilai persentil -def hitungNilaiPersentil(dataKelompok, dataKumulatif, persentil): - totalFrekuensi = hitungTotalFrekuensi(dataKelompok) - posisi = (persentil / nilaiPersen) * totalFrekuensi - - kelasInterval = next((item for item in dataKumulatif if item['kumulatif'] >= posisi), None) - - if kelasInterval: - batasBawah, batasAtas = kelasInterval['interval'] - kumulatifBawah = dataKumulatif[dataKumulatif.index(kelasInterval) - 1]['kumulatif'] if dataKumulatif.index(kelasInterval) > 0 else 0 - frekuensiDalamKelas = kelasInterval['frekuensi'] - - return batasBawah + ((posisi - kumulatifBawah) / frekuensiDalamKelas) * (batasAtas - batasBawah) - - return 0 # Atau nilai default yang sesuai jika tidak ditemukan kelasInterval - -# Menghitung nilai persentil ke-50 -hasilPersentil = hitungNilaiPersentil(dataKelompok, hitungDataKumulatif(dataKelompok), nilaiPersentil) # 17.5 -print(hasilPersentil) -``` - -::: - -## Desil -Desil merupakan pembagian N data yang urut menjadi 10 bagian yang mana data tersebut dibagi sama banyak tersebut, sehingga terdapat 9 nilai desil. Desil dibagi menjadi dua menurut jenis datanya, yaitu Data Tunggal dan Data Berkelompok. - -Data tunggal secara umum merupakan deret angka yang terdapat pada sebuah baris atau *array*. Rumus untuk menghitung desil data tunggal adalah sebagai berikut -$$ Di = \frac{i(n+1)}{10} $$ - -| Simbol | Pengertian | -| ------------- | ------------------------------------- | -| $D_i$ | Desil ke-i | -| i | Nilai Desil (1 hingga 9) | -| n | Banyaknya data pada baris atau *array*| - -Berikut ini contoh *case* dari desil data tunggal dan data berkelompok (menggunakan data sebelumnya) - -### Data Tunggal -Misalnya ada baris angka seperti dibawah dan kita ingin mencari desil ke-5 - -:::tabs -== JavaScript -```javascript -// Data Tunggal -const dataTunggal = [25, 27, 29, 18, 20, 21, 23, 10, 12, 14, 16]; - -const nilaiPersen = 10 -const nilaiDesil = 5; //1-9 -let totalDesil = 0; - -// Mengurutkan data secara ascending -const dataTersortir = [...dataTunggal].sort((a, b) => a - b); -const ukuranData = dataTunggal.length; - -// Menghitung posisi dari nilai desil -const posisi = (nilaiDesil * (ukuranData + 1)) / nilaiPersen; - -if (Number.isInteger(posisi)) { - totalDesil = dataTersortir[posisi - 1]; //20 -} else { - const indeksBawah = Math.floor(posisi) - 1; - const indeksAtas = Math.ceil(posisi) - 1; - - const nilaiBawah = dataTersortir[indeksBawah]; - const nilaiAtas = dataTersortir[indeksAtas]; - - // Interpolasi untuk menghitung nilai desil - totalDesil = nilaiBawah + (nilaiAtas - nilaiBawah) * (posisi - Math.floor(posisi)); //20 -} -``` -==Python -```python -# Data tunggal -dataTunggal = [25, 27, 29, 18, 20, 21, 23, 10, 12, 14, 16] - -nilaiPersen = 10 -nilaiDesil = 5 # 1-9 -totalDesil = 0 - -# Mengurutkan data secara ascending -dataTersortir = sorted(dataTunggal) -ukuranData = len(dataTunggal) - -# Menghitung posisi dari nilai desil -posisi = (nilaiDesil * (ukuranData + 1)) / nilaiPersen - -if posisi.is_integer(): - totalDesil = dataTersortir[int(posisi) - 1] # 20 -else: - indeksBawah = int(posisi) - 1 - indeksAtas = indeksBawah + 1 - - nilaiBawah = dataTersortir[indeksBawah] - nilaiAtas = dataTersortir[indeksAtas] - - # Interpolasi untuk menghitung nilai desil - totalDesil = nilaiBawah + (nilaiAtas - nilaiBawah) * (posisi - int(posisi)) # 20 - -print(totalDesil) -``` - -::: - -### Data Berkelompok -Berikut ini rumus desil untuk data berkelompok - -$$ D_i = L + \frac{i/10 - \sum f_b}{f_i} \times c $$ - -| Simbol | Pengertian | -| ------------- | --------------------------------------------------------------------- | -| $D_i$ | Nilai desil ke-i | -| L | Batas bawah kelas interval yang memuat $D_i$ | -| i | Nilai desil (1 hingga 9) | -| $\sum f_b$ | Jumlah frekuensi kumulatif sebelum kelas interval yang memuat $D_i$ | -| $f_i$ | Frekuensi kelas interval yang memuat $D_i$ | -| c | Panjang kelas interval yang memuat $D_i$ | - -Misalnya ada data kelompok umur warga dibawah 1 tahun hingga 40 tahun seperti dibawah dan kita ingin mencari desil ke-9 dari kelompok data tersebut -:::tabs -== JavaScript -```javascript -// Data kelompok -const dataKelompok = [ - { interval: [0, 10], frekuensi: 5 }, - { interval: [10, 20], frekuensi: 10 }, - { interval: [20, 30], frekuensi: 8 }, - { interval: [30, 40], frekuensi: 2 } -]; - -const nilaiDesil = 9; // 1-9 untuk desil ke-1 hingga ke-9 -const nilaiAwal = 0; -const nilaiPersen = 10; -let hasilDesil = 0 - -// Fungsi untuk menghitung total frekuensi -function hitungTotalFrekuensi(data) { - return data.reduce((jumlah, item) => jumlah + item.frekuensi, nilaiAwal); -} - -// Fungsi untuk menghitung data kumulatif -function hitungDataKumulatif(data) { - let frekuensiKumulatif = 0; - return data.map(item => { - frekuensiKumulatif += item.frekuensi; - return { ...item, kumulatif: frekuensiKumulatif }; - }); -} - -// Fungsi untuk menghitung nilai desil -function hitungNilaiDesil(dataKelompok, dataKumulatif, desil) { - const totalFrekuensi = hitungTotalFrekuensi(dataKelompok); - const posisi = (desil / nilaiPersen) * totalFrekuensi; - - const kelasInterval = dataKumulatif.find(item => item.kumulatif >= posisi); - - if (kelasInterval) { - const [batasBawah, batasAtas] = kelasInterval.interval; - const kumulatifBawah = dataKumulatif[dataKumulatif.indexOf(kelasInterval) - 1]?.kumulatif || 0; - const frekuensiDalamKelas = kelasInterval.frekuensi; - - return batasBawah + ((posisi - kumulatifBawah) / frekuensiDalamKelas) * (batasAtas - batasBawah); - } - - return 0; // Atau nilai default yang sesuai jika tidak ditemukan kelasInterval -} - -// Menghitung nilai desil ke-9 -hasilDesil = hitungNilaiDesil(dataKelompok, hitungDataKumulatif(dataKelompok), nilaiDesil); //29.375 -``` - -==Python - -```python -# Data kelompok -dataKelompok = [ - {"interval": [0, 10], "frekuensi": 5}, - {"interval": [10, 20], "frekuensi": 10}, - {"interval": [20, 30], "frekuensi": 8}, - {"interval": [30, 40], "frekuensi": 2} -] - -nilaiDesil = 9 # 1-9 untuk desil ke-1 hingga ke-9 -nilaiAwal = 0 -nilaiPersen = 10 -hasilDesil = 0 - -# Fungsi untuk menghitung total frekuensi -def hitungTotalFrekuensi(data): - return sum(item["frekuensi"] for item in data) - -# Fungsi untuk menghitung data kumulatif -def hitungDataKumulatif(data): - frekuensiKumulatif = 0 - hasil = [] - for item in data: - frekuensiKumulatif += item["frekuensi"] - hasil.append({**item, "kumulatif": frekuensiKumulatif}) - return hasil - -# Fungsi untuk menghitung nilai desil -def hitungNilaiDesil(dataKelompok, dataKumulatif, desil): - totalFrekuensi = hitungTotalFrekuensi(dataKelompok) - posisi = (desil / nilaiPersen) * totalFrekuensi - - kelasInterval = next((item for item in dataKumulatif if item["kumulatif"] >= posisi), None) - - if kelasInterval: - batasBawah, batasAtas = kelasInterval["interval"] - kumulatifBawah = dataKumulatif[dataKumulatif.index(kelasInterval) - 1]["kumulatif"] if dataKumulatif.index(kelasInterval) > 0 else 0 - frekuensiDalamKelas = kelasInterval["frekuensi"] - - return batasBawah + ((posisi - kumulatifBawah) / frekuensiDalamKelas) * (batasAtas - batasBawah) - - return 0 # Atau nilai default yang sesuai jika tidak ditemukan kelasInterval - -# Menghitung nilai desil ke-9 -hasilDesil = hitungNilaiDesil(dataKelompok, hitungDataKumulatif(dataKelompok), nilaiDesil) # 29.375 -print(hasilDesil) -``` -::: - -## Kuartil - -Kuartil merupakan pembagian N data yang urut menjadi 4 bagian yang mana data tersebut dibagi sama banyak tersebut, sehingga terdapat 3 nilai kuartil. Kuartil dibagi menjadi dua menurut jenis datanya, yaitu Data Tunggal dan Data Berkelompok. - -Data tunggal secara umum merupakan deret angka yang terdapat pada sebuah baris atau array. Rumus untuk menghitung kuartil data tunggal adalah sebagai berikut: -$$ Qi = \frac{i(n+1)}{4} $$ - -| Simbol | Pengertian | -| ------------- | ------------------------------------- | -| Qi | Kuartil ke-i | -| i | Nilai Kuartil (1 hingga 9) | -| n | Banyaknya data pada baris atau *array*| - -### Data Tunggal -Misalnya ada baris angka seperti dibawah dan kita ingin mencari kuartil ke-2 - -:::tabs -== JavaScript -```javascript -// Data Tunggal -const dataTunggal = [25, 27, 29, 18, 20, 21, 23, 10, 12, 14, 16]; - -const nilaiPersen = 4; -const nilaiKuartil = 2; // 1-3 -let totalKuartil = 0; - -// Mengurutkan data secara ascending -const dataTersortir = [...dataTunggal].sort((a, b) => a - b); -const jumlahData = dataTunggal.length; - -// Menghitung posisi dari nilai kuartil -const posisi = (nilaiKuartil * (jumlahData + 1)) / nilaiPersen; - -if (Number.isInteger(posisi)) { - totalKuartil = dataTersortir[posisi - 1]; //20 -} else { - const indeksBawah = Math.floor(posisi) - 1; - const indeksAtas = Math.ceil(posisi) - 1; - - const nilaiBawah = dataTersortir[indeksBawah]; - const nilaiAtas = dataTersortir[indeksAtas]; - - // Interpolasi untuk menghitung nilai kuartil - totalKuartil = nilaiBawah + (nilaiAtas - nilaiBawah) * (posisi - Math.floor(posisi)); //20 -} -``` -::: - -### Data Berkelompok - -Berikut ini rumus kuartil untuk data berkelompok - -$$ Q_i = L + \frac{i/4 - \sum f_b}{f_i} \times c $$ - -| Simbol | Pengertian | -| ------------- | --------------------------------------------------------------------- | -| $Q_i$ | Nilai desil ke-i | -| L | Batas bawah kelas interval yang memuat $Q_i$ | -| i | Nilai desil (1 hingga 9) | -| $\sum f_b$ | Jumlah frekuensi kumulatif sebelum kelas interval yang memuat $Q_i$ | -| $f_i$ | Frekuensi kelas interval yang memuat $Q_i$ | -| c | Panjang kelas interval yang memuat $Q_i$ | - -Misalnya ada data kelompok umur warga dibawah 1 tahun hingga 40 tahun seperti dibawah dan kita ingin mencari kuartil ke-2 dari kelompok data tersebut -:::tabs -== JavaScript -```javascript -// Data kelompok -const dataKelompok = [ - { interval: [0, 10], frekuensi: 5 }, - { interval: [10, 20], frekuensi: 10 }, - { interval: [20, 30], frekuensi: 8 }, - { interval: [30, 40], frekuensi: 2 } -]; - -const jumlahPersen = 4; -const nilaiKuartil = 2; // 1-3 -const nilaiAwal = 0; -let hasilKuartil = 0 - -// Fungsi untuk menghitung total frekuensi -function hitungTotalFrekuensi(data) { - return data.reduce((jumlah, item) => jumlah + item.frekuensi, nilaiAwal); -} - -// Fungsi untuk menghitung data kumulatif -function hitungDataKumulatif(data) { - let frekuensiKumulatif = 0; - return data.map(item => { - frekuensiKumulatif += item.frekuensi; - return { ...item, kumulatif: frekuensiKumulatif }; - }); -} - -// Fungsi untuk menghitung nilai kuartil -function hitungNilaiKuartil(dataKelompok, dataKumulatif, kuartil) { - const totalFrekuensi = hitungTotalFrekuensi(dataKelompok); - const posisi = (kuartil / jumlahPersen) * totalFrekuensi; - - const kelasInterval = dataKumulatif.find(item => item.kumulatif >= posisi); - - if (kelasInterval) { - const [batasBawah, batasAtas] = kelasInterval.interval; - const kumulatifBawah = dataKumulatif[dataKumulatif.indexOf(kelasInterval) - 1]?.kumulatif || 0; - const frekuensiDalamKelas = kelasInterval.frekuensi; - - return batasBawah + ((posisi - kumulatifBawah) / frekuensiDalamKelas) * (batasAtas - batasBawah); - } - - return 0; // Atau nilai default yang sesuai jika tidak ditemukan kelasInterval -} - -// Menghitung nilai kuartil ke-2 -hasilKuartil = hitungNilaiKuartil(dataKelompok, hitungDataKumulatif(dataKelompok), nilaiKuartil); //17.5 -``` -== Kotlin -```kotlin -// Data kelompok -data class KelompokData(val interval: Pair, val frekuensi: Int) - -val dataKelompok = listOf( - KelompokData(0 to 10, 5), - KelompokData(10 to 20, 10), - KelompokData(20 to 30, 8), - KelompokData(30 to 40, 2) -) - -val nilaiDesil = 9 // 1-9 untuk desil ke-1 hingga ke-9 -val nilaiAwal = 0 -val nilaiPersen = 10 -var hasilDesil = 0.0 - -// Fungsi untuk menghitung total frekuensi -fun hitungTotalFrekuensi(data: List): Int { - return data.sumOf { it.frekuensi } -} - -// Fungsi untuk menghitung data kumulatif -fun hitungDataKumulatif(data: List): List { - var frekuensiKumulatif = 0 - return data.map { - frekuensiKumulatif += it.frekuensi - it.copy(frekuensi = frekuensiKumulatif) - } -} - -// Fungsi untuk menghitung nilai desil -fun hitungNilaiDesil(dataKelompok: List, dataKumulatif: List, desil: Int): Double { - val totalFrekuensi = hitungTotalFrekuensi(dataKelompok) - val posisi = (desil.toDouble() / nilaiPersen) * totalFrekuensi - - val kelasInterval = dataKumulatif.find { it.frekuensi >= posisi } - - kelasInterval?.let { - val (batasBawah, batasAtas) = it.interval - val kumulatifBawah = dataKumulatif.getOrNull(dataKumulatif.indexOf(it) - 1)?.frekuensi ?: 0 - val frekuensiDalamKelas = it.frekuensi - kumulatifBawah - - return batasBawah + ((posisi - kumulatifBawah) / frekuensiDalamKelas) * (batasAtas - batasBawah) - } - - return 0.0 // Atau nilai default yang sesuai jika tidak ditemukan kelasInterval -} - -// Menghitung nilai desil ke-9 -hasilDesil = hitungNilaiDesil(dataKelompok, hitungDataKumulatif(dataKelompok), nilaiDesil) -println(hasilDesil) // Output: 29.375 -``` -== C++ -```cpp -#include -#include -#include // untuk std::accumulate - -struct KelompokData { - std::pair interval; - int frekuensi; -}; - -int nilaiDesil = 9; // 1-9 untuk desil ke-1 hingga ke-9 -int nilaiAwal = 0; -int nilaiPersen = 10; -double hasilDesil = 0; - -// Fungsi untuk menghitung total frekuensi -int hitungTotalFrekuensi(const std::vector& data) { - return std::accumulate(data.begin(), data.end(), nilaiAwal, - [](int jumlah, const KelompokData& item) { - return jumlah + item.frekuensi; - }); -} - -// Fungsi untuk menghitung data kumulatif -std::vector hitungDataKumulatif(const std::vector& data) { - int frekuensiKumulatif = 0; - std::vector dataKumulatif; - - for (const auto& item : data) { - frekuensiKumulatif += item.frekuensi; - dataKumulatif.push_back({ item.interval, frekuensiKumulatif }); - } - - return dataKumulatif; -} - -// Fungsi untuk menghitung nilai desil -double hitungNilaiDesil(const std::vector& dataKelompok, const std::vector& dataKumulatif, int desil) { - int totalFrekuensi = hitungTotalFrekuensi(dataKelompok); - double posisi = (static_cast(desil) / nilaiPersen) * totalFrekuensi; - - auto kelasInterval = std::find_if(dataKumulatif.begin(), dataKumulatif.end(), - [posisi](const KelompokData& item) { - return item.frekuensi >= posisi; - }); - - if (kelasInterval != dataKumulatif.end()) { - int batasBawah = kelasInterval->interval.first; - int batasAtas = kelasInterval->interval.second; - int index = std::distance(dataKumulatif.begin(), kelasInterval); - int kumulatifBawah = (index > 0) ? dataKumulatif[index - 1].frekuensi : 0; - int frekuensiDalamKelas = kelasInterval->frekuensi - kumulatifBawah; - - return batasBawah + ((posisi - kumulatifBawah) / frekuensiDalamKelas) * (batasAtas - batasBawah); - } - - return 0.0; // Atau nilai default yang sesuai jika tidak ditemukan kelasInterval -} - -int main() { - std::vector dataKelompok = { - {{0, 10}, 5}, - {{10, 20}, 10}, - {{20, 30}, 8}, - {{30, 40}, 2} - }; - - // Menghitung nilai desil ke-9 - hasilDesil = hitungNilaiDesil(dataKelompok, hitungDataKumulatif(dataKelompok), nilaiDesil); - std::cout << hasilDesil << std::endl; // Output: 29.375 - - return 0; -} -``` -==Python -```python -# Data kelompok -dataKelompok = [ - {"interval": [0, 10], "frekuensi": 5}, - {"interval": [10, 20], "frekuensi": 10}, - {"interval": [20, 30], "frekuensi": 8}, - {"interval": [30, 40], "frekuensi": 2} -] - -jumlahPersen = 4 -nilaiKuartil = 2 # 1-3 -nilaiAwal = 0 -hasilKuartil = 0 - -# Fungsi untuk menghitung total frekuensi -def hitungTotalFrekuensi(data): - return sum(item["frekuensi"] for item in data) - -# Fungsi untuk menghitung data kumulatif -def hitungDataKumulatif(data): - frekuensiKumulatif = 0 - hasil = [] - for item in data: - frekuensiKumulatif += item["frekuensi"] - hasil.append({**item, "kumulatif": frekuensiKumulatif}) - return hasil - -# Fungsi untuk menghitung nilai kuartil -def hitungNilaiKuartil(dataKelompok, dataKumulatif, kuartil): - totalFrekuensi = hitungTotalFrekuensi(dataKelompok) - posisi = (kuartil / jumlahPersen) * totalFrekuensi - - kelasInterval = next((item for item in dataKumulatif if item["kumulatif"] >= posisi), None) - - if kelasInterval: - batasBawah, batasAtas = kelasInterval["interval"] - kumulatifBawah = dataKumulatif[dataKumulatif.index(kelasInterval) - 1]["kumulatif"] if dataKumulatif.index(kelasInterval) > 0 else 0 - frekuensiDalamKelas = kelasInterval["frekuensi"] - - return batasBawah + ((posisi - kumulatifBawah) / frekuensiDalamKelas) * (batasAtas - batasBawah) - - return 0 # Atau nilai default yang sesuai jika tidak ditemukan kelasInterval - -# Menghitung nilai kuartil ke-2 -hasilKuartil = hitungNilaiKuartil(dataKelompok, hitungDataKumulatif(dataKelompok), nilaiKuartil) # 17.5 -print(hasilKuartil) -``` -:::