diff --git a/README.md b/README.md index 3410778..11501b8 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,13 @@ -# 📐 ttCalculator v2.2.0 +# 📐 ttCalculator v2.3.0 [![GitHub release](https://img.shields.io/github/v/release/LilDosto/ttCalculator?color=brightgreen&label=S%C3%BCr%C3%BCm)](https://github.com/LilDosto/ttCalculator/releases) [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE) [![.NET](https://img.shields.io/badge/.NET-8.0--windows-purple.svg)](https://dotnet.microsoft.com/) [![Platform](https://img.shields.io/badge/Platform-Windows%20x64-lightgrey.svg)](https://microsoft.com) -**ttCalculator**, 128-bit yüksek hassasiyetli matematik motoru, gelişmiş nümerik yöntemler, matris dekompozisyonları, dinamik grafik çizimleri ve çok değişkenli analizler gerçekleştirebilen modern ve profesyonel bir masaüstü matematik yazılımıdır. +**ttCalculator**, 128-bit yüksek hassasiyetli matematik motoru, diferansiyel denklem çözücüleri (ODE & PDE), gelişmiş nümerik yöntemler, çoklu fonksiyon grafik stüdyosu, matris dekompozisyonları ve çok değişkenli analizler gerçekleştirebilen modern ve profesyonel bir masaüstü matematik yazılımıdır. -Tüm matematiksel çekirdek, 1.169 otomatik testten oluşan kapsamlı doğrulama paketinden **%100 başarıyla (0 hata)** geçirilmiş ve son kullanıcıya hazır hale getirilmiştir. +Tüm matematiksel çekirdek, otomatik test paketinden **%100 başarıyla (0 hata, 0 uyarı)** geçirilmiş ve son kullanıcıya hazır hale getirilmiştir. --- @@ -15,30 +15,48 @@ Tüm matematiksel çekirdek, 1.169 otomatik testten oluşan kapsamlı doğrulama Uygulamanın hazır derlenmiş Windows sürümünü (`ttCalculator.exe`) hemen çalıştırmak için: -1. **[Releases](https://github.com/LilDosto/ttCalculator/releases/tag/v2.2.0)** sayfasına gidin. -2. **`ttCalculator.exe`** (veya `ttCalculator-v2.2.0-win-x64.zip`) dosyasını indirin. +1. **[Releases](https://github.com/LilDosto/ttCalculator/releases/tag/v2.3.0)** sayfasına gidin. +2. **`ttCalculator.exe`** (veya `ttCalculator-v2.3.0-win-x64.zip`) dosyasını indirin. 3. Çift tıklayarak doğrudan çalıştırın — ek bağımlılık gerektirmez! --- ## 📁 Proje Mimarisi -Proje, modern ve temiz bir .NET 8 çözüm mimarisine sahiptir: +Proje, modern ve modüler bir .NET 8 WinForms çözüm mimarisine sahiptir: ``` ttCalculator/ ├── ttCalculator.sln # Ana Visual Studio / .NET Çözüm Dosyası ├── src/ │ └── ttCalculator/ # Masaüstü Uygulaması (WinForms / .NET 8) -│ ├── Controls/ # 9 Temel Arayüz Modülü ve Kullanıcı Kontrolleri -│ ├── Core/ # 128-bit Matematik, Matris ve Nümerik Yöntem Çekirdeği +│ ├── Controls/ # 13 Temel Arayüz Modülü ve Kullanıcı Kontrolleri +│ │ ├── SimpleCalculatorControl.cs +│ │ ├── GraphPlotterControl.cs # Gelişmiş Çoklu Eğri & Geometri Çizici +│ │ ├── CombinatoricsControl.cs +│ │ ├── RootFinderControl.cs # Çoklu Kök Taramalı Kök Bulucu +│ │ ├── SystemSolverControl.cs +│ │ ├── DerivativeCalculatorControl.cs +│ │ ├── MatrixCalculatorControl.cs +│ │ ├── TaylorSeriesControl.cs # Kesirli & Faktöriyelli Taylor +│ │ ├── MultivariableTaylorControl.cs +│ │ ├── OdeSolverControl.cs # 1D ODE Çözücü (Euler, RK4, RK8) +│ │ ├── OdeSystemSolverControl.cs # ODE Sistemi Çözücü +│ │ ├── PdeSolverControl.cs # 1D Kısmi Diferansiyel (Isı/Dalga/Taşınım) +│ │ └── PdeSystemSolverControl.cs # PDE Sistemi (Reaksiyon-Difüzyon) +│ ├── Core/ # 128-bit Matematik, ODE/PDE ve Nümerik Yöntem Çekirdeği +│ │ ├── DifferentialEquations.cs # Euler, Heun, RK4, RK8, FTCS, Leapfrog, Upwind +│ │ ├── NumericalMethods.cs # Çoklu Kök Tarama, Kesirli Açılım, Türev +│ │ ├── Function.cs # Hızlı İfade Derleyici +│ │ ├── DecimalMath.cs # 128-bit Yüksek Hassasiyetli Trigonometri/Logaritma +│ │ └── Matrix/ # LU, QR, Cholesky, Eigenvalue, SVD │ ├── MainForm.cs # Ana Pencere ve Akışkan Gezinme Yönetimi -│ ├── ThemeHelper.cs # Koyu Tema ve Çift Tamponlama (Double Buffering) +│ ├── ThemeHelper.cs # Modern Koyu Tema ve Çift Tamponlama │ ├── Program.cs # Tekil Örnek (Single-Instance Mutex) Giriş Noktası │ └── ttCalculator.csproj # Uygulama Proje Yapılandırması ├── tests/ -│ └── ttCalculator.Tests/ # Otomatik Doğrulama Testleri (1.169 Test) -│ └── ttCalculator.Tests.csproj +│ └── ttCalculator.Tests/ # Otomatik Doğrulama Testleri +│ └── Program.cs ├── Release/ # Taşınabilir Tek Dosya Dağıtımları ├── LICENSE # MIT Lisansı └── README.md @@ -48,75 +66,62 @@ ttCalculator/ ## ✨ Temel Özellikler & Modüller -Uygulama modern koyu tema (Dark Theme) arayüzü ile 9 ana modülden oluşmaktadır: +Uygulama modern koyu tema (Dark Theme) arayüzü ile 13 ana modülden oluşmaktadır: -### 1. 🔢 Basit & Bilimsel Hesap Makinesi -* **128-Bit Yüksek Hassasiyet:** Standart IEEE-754 çift duyarlılık kayıpları yerine tam hassasiyetli `decimal` aritmetik. -* **Açı Modu (RAD / DEG):** Tek tıkla Radyan / Derece birimi değişimi. -* **Kapsamlı Fonksiyon Desteği:** `sin`, `cos`, `tan`, `cot`, `asin`, `acos`, `atan`, `atan2`, `sinh`, `cosh`, `tanh`, `ln`, `log10`, `log(x, base)`, `exp`, `sqrt`, `cbrt`, `abs`, `max`, `min`. -* **Kullanıcı Kolaylıkları:** Otomatik parantez tamamlama, geçmiş (history) paneli ve çift tıklamayla geri yükleme, klavye kısayolları. +### 1. 📈 Gelişmiş Çoklu Fonksiyon & Geometri Grafiği Çizici (v2.3) +* **Çoklu Fonksiyon Desteği:** Aynı tuval üzerinde sınırsız sayıda fonksiyon çizimi; sağ panelden renk, çizgi tipi (Düz, Kesikli, Noktalı) ve kalınlık (1-4 px) değiştirme, açma/kapama ve silme. +* **Aralık Kısıtlama vs Tüm Ekran:** `Min X` ve `Max X` aralığına kısıtlı çizim veya $-\infty$ ile $+\infty$ arasında tam ekran çizim seçeneği. +* **Bağımsız Eksen Ölçekleme:** X eksenini Y'ye dokunmadan 10 kat veya serbestçe sündürme/daraltma (`Shift + Tekerlek` ile X sündürme, `Ctrl + Tekerlek` ile Y sündürme). +* **Tekil Nokta Yönetimi:** Tıklayarak veya koordinat girerek nokta ekleme; renk, boyut ve şekil (Daire, Kare, Çarpı, Elmas) seçimi; **nokta üzerine sağ tıklayarak veya listeden tekil silme**. +* **Ortak Teğet Doğrusu Çizici:** İki fonksiyon seçildiğinde aralarındaki ortak teğet doğrularını, değme noktalarını ve $y = m\cdot x + c$ doğru denklemini hesaplayıp grafiğe ekleme. +* **En Yakın Noktalar & Doğru:** Kesişmeyen iki fonksiyonun aralarındaki minimum mesafeyi veren en yakın noktaları ve bu noktalardan geçen dik doğru denklemini hesaplama. +* **Noktadan Teğet Çizici:** Dışarıdaki bir noktadan seçilen fonksiyona çizilen teğet doğru denklemi ve grafiği. +* **Hazır Parametrik Şekiller:** Daire, Kare, Dikdörtgen, Eşkenar Üçgen, Elips ve Düzgün Altıgen şekillerini parametrik olarak fonksiyon listesine ekleyip çizdirme. -### 2. 🔍 Tek Değişkenli Kök Bulucu (Root Finder) -* **Newton-Raphson Yöntemi:** $f(x) / f'(x)$ teğet tabanlı hızlı yakınsama. -* **Bisection (İkiye Bölme):** Garantili yakınsama ve uç nokta kök tespiti ($f(a)=0$ veya $f(b)=0$). -* **Secant (Kiriş):** İki başlangıç noktası üzerinden türevsiz yaklaşım. -* **Regula Falsi (Illinois Hızlandırmalı):** Dışbükey fonksiyonlardaki durgunluk (stagnation) sorununu çözen Illinois algoritması. -* **Dinamik Değişken Desteği:** $x, t, y$ veya istenen herhangi bir değişken adıyla kök bulma. +### 2. ∫ Diferansiyel Denklem Çözücü (1 Değişkenli ODE) +* **Desteklenen Algoritmalar:** Euler (1. Derece), Heun (RK2 Predictor-Corrector), Runge-Kutta 4 (RK4) ve 8. Derece Yüksek Hassasiyetli Runge-Kutta (RK8). +* Başlangıç değer problemi ($y' = f(x, y)$, $y(x_0) = y_0$) için adım büyüklüğü, eğimler ve adım adım çözüm tablosu. -### 3. 📉 Sayısal & Kısmi Türev Hesaplayıcı -* **Farklı Türev Formülleri:** Merkezi sonlu farklar ($O(h^4)$ ve $O(h^6)$ hassasiyet), İleri Binom ve Geri Sonlu Farklar. -* **1. ile 12. Derece Arası Türev:** Yüksek mertebeli türevler için optimize edilmiş adım büyüklüğü ($h$) ve koşullandırma. -* **Çok Değişkenli Kısmi Türev:** İstenen değişkene göre kısmi türev alma ($f(x, y, z)$). +### 3. ∭ Diferansiyel Denklem Sistemi Çözücü (System of ODEs) +* Vektörel diferansiyel denklem sistemleri: $\frac{d\vec{Y}}{dt} = \vec{F}(t, \vec{Y})$. +* **Yüksek Dereceli ODE Dönüşümü:** $n$. derece diferansiyel denklemleri durum-uzayı (state-space) vektör sistemine dönüştürerek çözebilme. +* **Hazır Modeller:** Harmonik Osilatör, Av-Avcı (Lotka-Volterra), Sönümlü Sarkaç, Lorenz Kaotik Çekicisi. +* Vektörel Euler, RK4 ve RK8 çözücüleri ile zaman adımları tablosu. -### 4. 📜 Taylor Serisi Açılımı (Tek Değişkenli) -* İstenen merkez noktası ($a$) etrafında $n$. dereceden sembolik Taylor polinom açılımı. -* Noktadaki türevler ve terim katsayıları tablosu. +### 4. 🌊 Kısmi Diferansiyel Denklem Çözücü (1D PDE) +* **1 Boyutlu Isı Denklemi:** $u_t = \alpha \cdot u_{xx}$ (FTCS sonlu farklar yöntemi, kararlılık koşulu $r \le 0.5$ denetimi). +* **1 Boyutlu Dalga Denklemi:** $u_{tt} = c^2 \cdot u_{xx}$ (Leapfrog merkezi farklar, Courant-Friedrichs-Lewy / CFL denetimi). +* **1 Boyutlu Taşınım (Advection) Denklemi:** $u_t + v \cdot u_x = 0$ (Upwind stabil şeması). +* Farklı zaman dilimlerinde ($t=0, T/4, T/2, 3T/4, T$) mekan profili tablosu. -### 5. 🌐 Çok Değişkenli Taylor Serisi -* $f(x, y)$, $f(x, y, z)$ fonksiyonlarının $(x_0, y_0, \dots)$ noktası etrafında çok değişkenli polinom yaklaşımı. -* Sayısal türev kalıntılarını filtreleyen rasyonel katsayı yakalama algoritması. +### 5. 🌀 Kısmi Diferansiyel Denklem Sistemi Çözücü (Coupled PDE System) +* 1 Boyutlu Bağlaşımlı Reaksiyon-Difüzyon Sistemleri: + $$u_t = D_u \cdot u_{xx} + F(u, v)$$ + $$v_t = D_v \cdot v_{xx} + G(u, v)$$ +* Sıfır-akı (Neumann) sınır koşulları, Turing deseni oluşumu (Gray-Scott, Schnakenberg, FitzHugh-Nagumo modelleri). -### 6. ⚖️ Doğrusal & Doğrusal Olmayan Denklem Sistemleri -* **LU Ayrışımı (A = P·L·U):** Doğrusal sistemler için doğrudan en hızlı çözücü. -* **Ters Matris ($X = A^{-1} \cdot b$):** Analitik ters matris çarpımı. -* **QR Ayrışımı ($Q \cdot R \cdot X = b$):** Householder ortogonal dönüşümü. -* **Gauss-Seidel İterasyonu:** Köşegen baskınlık denetimli ardışık iteratif çözücü. -* **Çok Boyutlu Newton-Raphson:** Doğrusal olmayan (polinom, trigonometrik, üstel vb.) karmaşık sistem çözücü. -* **Doğrusallık Denetimi:** Lineer çözücüye non-lineer denklem verildiğinde otomatik uyarı. +### 6. 🔍 Çoklu Kök Taramalı Kök Bulucu (Root Finder) +* **🎯 Otomatik Çoklu Kök Taraması:** Verilen $[a, b]$ aralığındaki tüm tekil ve çoklu kökleri ardışık/paralel nümerik tarama ile bularak temiz bir kök tablosunda sunar. +* **Klasik Nümerik Yöntemler:** Newton-Raphson, Bisection (İkiye Bölme), Secant (Kiriş), Regula Falsi (Illinois hızlandırmalı). -### 7. 🧮 Gelişmiş Matris Hesaplayıcı & 5 Temel Ayrışım -* **5 Temel Dekompozisyon:** - * **LU Ayrışımı:** $L \cdot U = P \cdot A$ - * **QR Ayrışımı:** $Q \cdot R = A$ - * **Cholesky Ayrışımı:** $L \cdot L^T = A$ (Pozitif tanımlı denetimi) - * **Özdeğer & Özvektör:** $\det(A - \lambda I) = 0$ - * **Tekil Değer Ayrışımı (SVD):** Kare ($n \times n$) ve Dikdörtgen ($m \times n$, $m < n$ ve $m > n$) tam destek ($U \cdot S \cdot V^T = A$). -* **Matris Aritmetiği:** Toplama, çıkarma, matris çarpımı, eleman bazlı çarpma/bölme, skaler çarpım. -* **Matris Analizi:** Determinant, İz (Trace), Rank, 1-Norm, 2-Norm, Sonsuz-Norm, Frobenius Normu, Kondisyon Sayısı. -* **Matris Denklem Çözümü:** $A \cdot X = B$ ve $A^T \cdot X = B$. +### 7. 📜 Taylor Serisi Açılımı (Kesirli & Faktöriyelli Form) +* Tek ve çok değişkenli Taylor açılımlarında katsayılar hem ondalıklı, hem **sadeleştirilmiş kesirli formda**, hem de formülasyona tam uygun **analitik faktöriyelli formda** ($\frac{f^{(k)}(a)}{k!}$) gösterilir. ### 8. 🎲 Kombinatorik, Polar Dönüşüm ve Özel Fonksiyonlar -* **Taşmasız Kombinatorik:** $C(n, k)$ ve $P(n, k)$ çarpımsal sadeleştirme ile $52!$ gibi $10^{67}$ değerlerine çıkmadan $C(52, 5) = 2.598.960$ hesaplar. -* **Pascal Üçgeni:** $n$. dereceye kadar binom katsayıları tablosu. -* **Karakter Kombinasyon Üreteci:** Belirtilen alfabeden istenen boyutta tüm dizilimleri türetme. -* **Kartezyen $\leftrightarrow$ Polar Dönüşüm:** Hipotenüs ve açı hesabı ($r, \theta$ rad ve derece). +* Düzeltilmiş Taban ($b$) arayüz kutusu, taşmasız $C(n, k)$ ve $P(n, k)$ kombinatorik motoru, Pascal üçgeni ve polar/kartezyen dönüşümler. -### 9. 📊 Dinamik Fonksiyon & Grafik Çizici -* **Asimptot & Süreksizlik Algılama:** $\tan(x)$ ve $\frac{1}{x^2-1}$ gibi fonksiyonlarda dikey çizgi hataları önleyen eğri parçalama. -* **İnteraktif Tuval:** Fare ile eksen kaydırma (Pan), tekerlek ile yakınlaştırma (Zoom), tıklama ile nokta işaretleme. -* **Otomatik Eksen Ölçekleme (Auto-fit):** Fonksiyon genliğine göre Y eksenini otomatik sığdırma. +### 9. 🔢 Basit & Bilimsel Hesap Makinesi +* 128-bit `decimal` motoru, RAD/DEG modları, otomatik parantez tamamlama ve geçmiş paneli. + +### 10. ⚖️ Doğrusal & Doğrusal Olmayan Denklem Sistemleri +* LU, QR, Ters Matris, Gauss-Seidel ve Çok Boyutlu Newton-Raphson çözücüleri. + +### 11. 🧮 Gelişmiş Matris Hesaplayıcı & 5 Temel Ayrışım +* LU, QR, Cholesky, Özdeğer/Özvektör ve SVD (Tekil Değer Ayrışımı) dekompozisyonları. --- -## 🛡️ Güvenilirlik & Sistem Kararlılığı - -* **Tek Kopya Çalışma (Single Instance Mutex):** Uygulama arka planda zaten açıkken ikinci kez açıldığında var olan pencere öne getirilir ve odaklanır. -* **Temiz Süreç Sonlandırma (Zero Background Leakage):** Pencere kapatıldığında arka planda hiçbir süreç veya iş parçacığı asılı kalmaz (`Environment.Exit(0)`). -* **Test Doğrulaması:** 1.169 adet birim ve uçtan uca otomatik testin tamamı %100 başarıyla geçmektedir. - ---- - -## 🛠️ Kaynak Koddan Derleme +## 🛠️ Kaynak Koddan Derleme & Yayımlama ```bash # Depoyu klonlayın diff --git a/src/ttCalculator/Controls/CombinatoricsControl.Designer.cs b/src/ttCalculator/Controls/CombinatoricsControl.Designer.cs index cb137c7..f4efe2f 100644 --- a/src/ttCalculator/Controls/CombinatoricsControl.Designer.cs +++ b/src/ttCalculator/Controls/CombinatoricsControl.Designer.cs @@ -221,20 +221,24 @@ namespace MathApp.Controls // Group 4: Special Functions StyleGroupBox(grpSpecial, "4. Hiperbolik, Ters Trig & Özel Logaritma", new Point(12, 414), new Size(350, 105)); - StyleLabel(lblSpecialX, "x:", new Point(15, 24)); - this.txtSpecialX.Location = new Point(36, 21); - this.txtSpecialX.Size = new Size(80, 23); + StyleLabel(lblSpecialX, "x:", new Point(12, 24)); + this.txtSpecialX.Location = new Point(32, 21); + this.txtSpecialX.Size = new Size(75, 24); this.txtSpecialX.BackColor = Color.FromArgb(40, 43, 56); this.txtSpecialX.ForeColor = Color.White; this.txtSpecialX.BorderStyle = BorderStyle.FixedSingle; + this.txtSpecialX.Font = new Font("Consolas", 9.5F); + this.txtSpecialX.TextAlign = HorizontalAlignment.Center; this.txtSpecialX.Text = "0.75"; - StyleLabel(lblBase, "Taban b:", new Point(130, 24)); - this.txtBase.Location = new Point(188, 21); - this.txtBase.Size = new Size(50, 23); + StyleLabel(lblBase, "Taban (b):", new Point(125, 24)); + this.txtBase.Location = new Point(200, 21); + this.txtBase.Size = new Size(85, 24); this.txtBase.BackColor = Color.FromArgb(40, 43, 56); this.txtBase.ForeColor = Color.White; this.txtBase.BorderStyle = BorderStyle.FixedSingle; + this.txtBase.Font = new Font("Consolas", 9.5F); + this.txtBase.TextAlign = HorizontalAlignment.Center; this.txtBase.Text = "2"; StyleActionBtn(btnSpecialCalc, "sinh, cosh, asin, acos, atan, log Hesapla", new Point(15, 54), new Size(320, 26)); diff --git a/src/ttCalculator/Controls/GraphPlotterControl.Designer.cs b/src/ttCalculator/Controls/GraphPlotterControl.Designer.cs index 84c08b6..196f6b5 100644 --- a/src/ttCalculator/Controls/GraphPlotterControl.Designer.cs +++ b/src/ttCalculator/Controls/GraphPlotterControl.Designer.cs @@ -20,8 +20,8 @@ namespace MathApp.Controls private void InitializeComponent() { this.pnlHeader = ThemeHelper.CreateHeaderPanel( - "Etkileşimli Fonksiyon Grafiği Çizici (Graph Plotter)", - "Gerçek zamanlı yakınlaştırma (Zoom), kaydırma (Pan), asimptot algılama ve eğri üzerinde koordinat inceleme."); + "Gelişmiş Çoklu Fonksiyon & Geometri Grafiği Çizici (Advanced Graph Plotter)", + "Çoklu fonksiyon desteği, ortak teğetler, en yakın nokta analizi, eksen sündürme, hazır parametrik şekiller ve tekil nokta yönetimi."); this.pnlControls = new Panel(); this.pnlPresets = new FlowLayoutPanel(); @@ -37,97 +37,513 @@ namespace MathApp.Controls this.txtMinX = new TextBox(); this.lblMaxX = new Label(); this.txtMaxX = new TextBox(); - this.btnPlot = ThemeHelper.CreateActionButton("📈 Grafiği Çiz", 130, 32, true); - this.btnResetView = ThemeHelper.CreateActionButton("🔄 Sıfırla", 100, 32, false); - this.btnClearMarks = ThemeHelper.CreateActionButton("📍 Noktaları Sil", 130, 32, false); + this.chkClampRange = new CheckBox(); + this.btnPlot = ThemeHelper.CreateActionButton("➕ Çiz / Ekle", 110, 28, true); + + // Scale Toolbar buttons + this.btnZoomXIn = ThemeHelper.CreateActionButton("↔️ X Sündür (+)", 105, 26, false); + this.btnZoomXOut = ThemeHelper.CreateActionButton("X Daralt (-)", 90, 26, false); + this.btnZoomX10 = ThemeHelper.CreateActionButton("X: 10×", 65, 26, false); + this.btnZoomYIn = ThemeHelper.CreateActionButton("↕️ Y Sündür (+)", 105, 26, false); + this.btnZoomYOut = ThemeHelper.CreateActionButton("Y Daralt (-)", 90, 26, false); + this.btnAspect1to1 = ThemeHelper.CreateActionButton("1:1 Oran", 75, 26, false); + this.btnResetView = ThemeHelper.CreateActionButton("🔄 Sıfırla", 75, 26, false); + + this.pnlRightSide = new Panel(); + this.tabManager = new TabControl(); + this.tabFunctions = new TabPage(); + this.tabPoints = new TabPage(); + this.tabTools = new TabPage(); + this.tabShapes = new TabPage(); + + // Function Tab Controls + this.lstCurves = new ListBox(); + this.btnCurveColor = new Button(); + this.cmbCurveStyle = new ComboBox(); + this.cmbCurveThickness = new ComboBox(); + this.btnCurveToggle = new Button(); + this.btnCurveDelete = new Button(); + this.btnCurveClearAll = new Button(); + + // Points Tab Controls + this.lstPoints = new ListBox(); + this.lblPtX = new Label(); + this.txtPtX = new TextBox(); + this.lblPtY = new Label(); + this.txtPtY = new TextBox(); + this.lblPtShape = new Label(); + this.cmbPtShape = new ComboBox(); + this.btnPtColor = new Button(); + this.btnAddPoint = new Button(); + this.btnDeletePoint = new Button(); + this.btnClearPoints = new Button(); + this.lblPointHint = new Label(); + + // Tools Tab Controls + this.lblToolF1 = new Label(); + this.cmbToolF1 = new ComboBox(); + this.lblToolF2 = new Label(); + this.cmbToolF2 = new ComboBox(); + this.btnCommonTangent = ThemeHelper.CreateActionButton("📐 Ortak Teğet Doğrusunu Bul", 260, 30, true); + this.btnNearestPoints = ThemeHelper.CreateActionButton("📍 En Yakın Noktalar & Doğru", 260, 30, false); + this.lblToolSep = new Label(); + this.lblToolPointTan = new Label(); + this.txtTanPointX = new TextBox(); + this.txtTanPointY = new TextBox(); + this.btnPointTangent = ThemeHelper.CreateActionButton("📏 Noktadan Teğet Çiz", 260, 30, false); + this.txtToolLog = new RichTextBox(); + + // Shapes Tab Controls + this.lblShapeType = new Label(); + this.cmbShapeType = new ComboBox(); + this.lblShapeCenter = new Label(); + this.txtShapeCenterX = new TextBox(); + this.txtShapeCenterY = new TextBox(); + this.lblShapeDim1 = new Label(); + this.txtShapeDim1 = new TextBox(); + this.lblShapeDim2 = new Label(); + this.txtShapeDim2 = new TextBox(); + this.btnAddShape = ThemeHelper.CreateActionButton("📐 Şekli Grafiğe Ekle", 260, 32, true); this.pnlStatusBar = new Panel(); this.lblStatus = new Label(); this.pnlCanvas = new Panel(); this.pnlControls.SuspendLayout(); + this.pnlRightSide.SuspendLayout(); + this.tabManager.SuspendLayout(); + this.tabFunctions.SuspendLayout(); + this.tabPoints.SuspendLayout(); + this.tabTools.SuspendLayout(); + this.tabShapes.SuspendLayout(); this.pnlStatusBar.SuspendLayout(); this.SuspendLayout(); // pnlControls this.pnlControls.Dock = DockStyle.Top; - this.pnlControls.Height = 96; + this.pnlControls.Height = 104; this.pnlControls.BackColor = ThemeHelper.DarkBackground; - this.pnlControls.Padding = new Padding(24, 8, 24, 8); + this.pnlControls.Padding = new Padding(16, 6, 16, 6); - this.lblPresets.Text = "Hızlı Fonksiyonlar:"; + this.lblPresets.Text = "Hızlı:"; this.lblPresets.AutoSize = true; this.lblPresets.ForeColor = ThemeHelper.MutedText; - this.lblPresets.Font = new Font("Segoe UI Semibold", 9.5F, FontStyle.Bold); - this.lblPresets.Margin = new Padding(0, 5, 10, 0); + this.lblPresets.Font = new Font("Segoe UI Semibold", 9F, FontStyle.Bold); + this.lblPresets.Margin = new Padding(0, 4, 6, 0); - this.pnlPresets.Location = new Point(24, 8); - this.pnlPresets.Size = new Size(820, 34); - this.pnlPresets.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + this.pnlPresets.Location = new Point(16, 6); + this.pnlPresets.Size = new Size(950, 30); this.pnlPresets.Controls.Add(this.lblPresets); this.pnlPresets.Controls.Add(this.btnEx1); this.pnlPresets.Controls.Add(this.btnEx2); this.pnlPresets.Controls.Add(this.btnEx3); this.pnlPresets.Controls.Add(this.btnEx4); - int y = 52; - + int yRow1 = 40; this.lblEquation.AutoSize = true; this.lblEquation.ForeColor = ThemeHelper.LightText; - this.lblEquation.Font = new Font("Segoe UI Semibold", 10.5F, FontStyle.Bold); + this.lblEquation.Font = new Font("Segoe UI Semibold", 9.5F, FontStyle.Bold); this.lblEquation.Text = "f(x) ="; - this.lblEquation.Location = new Point(24, y + 3); + this.lblEquation.Location = new Point(16, yRow1 + 3); - this.txtEquation.Location = new Point(74, y); - this.txtEquation.Size = new Size(210, 27); + this.txtEquation.Location = new Point(60, yRow1); + this.txtEquation.Size = new Size(180, 25); this.txtEquation.Text = "sin(x)"; - this.txtEquation.Font = new Font("Consolas", 11F); + this.txtEquation.Font = new Font("Consolas", 10.5F); this.txtEquation.BackColor = ThemeHelper.CardBackground; this.txtEquation.ForeColor = Color.White; this.txtEquation.BorderStyle = BorderStyle.FixedSingle; this.lblMinX.AutoSize = true; this.lblMinX.ForeColor = ThemeHelper.LightText; - this.lblMinX.Font = new Font("Segoe UI", 9.5F); this.lblMinX.Text = "Min X:"; - this.lblMinX.Location = new Point(296, y + 4); + this.lblMinX.Location = new Point(250, yRow1 + 4); - this.txtMinX.Location = new Point(344, y); - this.txtMinX.Size = new Size(55, 27); + this.txtMinX.Location = new Point(292, yRow1); + this.txtMinX.Size = new Size(50, 25); this.txtMinX.Text = "-10"; - this.txtMinX.Font = new Font("Consolas", 10.5F); + this.txtMinX.Font = new Font("Consolas", 9.5F); this.txtMinX.BackColor = ThemeHelper.CardBackground; this.txtMinX.ForeColor = Color.White; this.txtMinX.BorderStyle = BorderStyle.FixedSingle; this.lblMaxX.AutoSize = true; this.lblMaxX.ForeColor = ThemeHelper.LightText; - this.lblMaxX.Font = new Font("Segoe UI", 9.5F); this.lblMaxX.Text = "Max X:"; - this.lblMaxX.Location = new Point(408, y + 4); + this.lblMaxX.Location = new Point(348, yRow1 + 4); - this.txtMaxX.Location = new Point(458, y); - this.txtMaxX.Size = new Size(55, 27); + this.txtMaxX.Location = new Point(392, yRow1); + this.txtMaxX.Size = new Size(50, 25); this.txtMaxX.Text = "10"; - this.txtMaxX.Font = new Font("Consolas", 10.5F); + this.txtMaxX.Font = new Font("Consolas", 9.5F); this.txtMaxX.BackColor = ThemeHelper.CardBackground; this.txtMaxX.ForeColor = Color.White; this.txtMaxX.BorderStyle = BorderStyle.FixedSingle; - this.btnPlot.Location = new Point(525, y - 2); - this.btnResetView.Location = new Point(663, y - 2); - this.btnClearMarks.Location = new Point(771, y - 2); + this.chkClampRange.Text = "Aralıkta Kısıtla"; + this.chkClampRange.ForeColor = ThemeHelper.LightText; + this.chkClampRange.Location = new Point(452, yRow1 + 3); + this.chkClampRange.Size = new Size(110, 22); + + this.btnPlot.Location = new Point(570, yRow1 - 1); + + int yRow2 = 72; + this.btnZoomXIn.Location = new Point(16, yRow2); + this.btnZoomXOut.Location = new Point(126, yRow2); + this.btnZoomX10.Location = new Point(221, yRow2); + this.btnZoomYIn.Location = new Point(291, yRow2); + this.btnZoomYOut.Location = new Point(401, yRow2); + this.btnAspect1to1.Location = new Point(496, yRow2); + this.btnResetView.Location = new Point(576, yRow2); this.pnlControls.Controls.Add(this.pnlPresets); - this.pnlControls.Controls.Add(this.btnClearMarks); - this.pnlControls.Controls.Add(this.btnResetView); - this.pnlControls.Controls.Add(this.btnPlot); - this.pnlControls.Controls.Add(this.txtMaxX); - this.pnlControls.Controls.Add(this.lblMaxX); - this.pnlControls.Controls.Add(this.txtMinX); - this.pnlControls.Controls.Add(this.lblMinX); - this.pnlControls.Controls.Add(this.txtEquation); this.pnlControls.Controls.Add(this.lblEquation); + this.pnlControls.Controls.Add(this.txtEquation); + this.pnlControls.Controls.Add(this.lblMinX); + this.pnlControls.Controls.Add(this.txtMinX); + this.pnlControls.Controls.Add(this.lblMaxX); + this.pnlControls.Controls.Add(this.txtMaxX); + this.pnlControls.Controls.Add(this.chkClampRange); + this.pnlControls.Controls.Add(this.btnPlot); + this.pnlControls.Controls.Add(this.btnZoomXIn); + this.pnlControls.Controls.Add(this.btnZoomXOut); + this.pnlControls.Controls.Add(this.btnZoomX10); + this.pnlControls.Controls.Add(this.btnZoomYIn); + this.pnlControls.Controls.Add(this.btnZoomYOut); + this.pnlControls.Controls.Add(this.btnAspect1to1); + this.pnlControls.Controls.Add(this.btnResetView); + + // pnlRightSide (Tabbed Manager) + this.pnlRightSide.Dock = DockStyle.Right; + this.pnlRightSide.Width = 320; + this.pnlRightSide.BackColor = ThemeHelper.CardBackground; + this.pnlRightSide.Padding = new Padding(4); + + this.tabManager.Dock = DockStyle.Fill; + this.tabManager.Controls.Add(this.tabFunctions); + this.tabManager.Controls.Add(this.tabPoints); + this.tabManager.Controls.Add(this.tabTools); + this.tabManager.Controls.Add(this.tabShapes); + + // tabFunctions + this.tabFunctions.Text = "📈 Eğriler"; + this.tabFunctions.BackColor = ThemeHelper.DarkBackground; + this.tabFunctions.Padding = new Padding(8); + + this.lstCurves.Dock = DockStyle.Top; + this.lstCurves.Height = 220; + this.lstCurves.BackColor = Color.FromArgb(11, 17, 32); + this.lstCurves.ForeColor = Color.White; + this.lstCurves.Font = new Font("Consolas", 9.5F); + + this.btnCurveColor.Text = "🎨 Renk"; + this.btnCurveColor.Size = new Size(85, 26); + this.btnCurveColor.Location = new Point(8, 230); + this.btnCurveColor.BackColor = Color.FromArgb(30, 41, 59); + this.btnCurveColor.ForeColor = Color.White; + this.btnCurveColor.FlatStyle = FlatStyle.Flat; + + this.cmbCurveStyle.Location = new Point(100, 230); + this.cmbCurveStyle.Size = new Size(95, 25); + this.cmbCurveStyle.DropDownStyle = ComboBoxStyle.DropDownList; + this.cmbCurveStyle.BackColor = ThemeHelper.CardBackground; + this.cmbCurveStyle.ForeColor = Color.White; + this.cmbCurveStyle.Items.AddRange(new object[] { "Düz Çizgi", "Kesikli", "Noktalı" }); + this.cmbCurveStyle.SelectedIndex = 0; + + this.cmbCurveThickness.Location = new Point(202, 230); + this.cmbCurveThickness.Size = new Size(90, 25); + this.cmbCurveThickness.DropDownStyle = ComboBoxStyle.DropDownList; + this.cmbCurveThickness.BackColor = ThemeHelper.CardBackground; + this.cmbCurveThickness.ForeColor = Color.White; + this.cmbCurveThickness.Items.AddRange(new object[] { "1 px", "2 px", "3 px", "4 px" }); + this.cmbCurveThickness.SelectedIndex = 1; + + this.btnCurveToggle.Text = "👁️ Göster/Gizle"; + this.btnCurveToggle.Size = new Size(138, 28); + this.btnCurveToggle.Location = new Point(8, 265); + this.btnCurveToggle.BackColor = Color.FromArgb(30, 41, 59); + this.btnCurveToggle.ForeColor = Color.White; + this.btnCurveToggle.FlatStyle = FlatStyle.Flat; + + this.btnCurveDelete.Text = "🗑️ Eğriyi Sil"; + this.btnCurveDelete.Size = new Size(138, 28); + this.btnCurveDelete.Location = new Point(154, 265); + this.btnCurveDelete.BackColor = Color.FromArgb(153, 27, 27); + this.btnCurveDelete.ForeColor = Color.White; + this.btnCurveDelete.FlatStyle = FlatStyle.Flat; + + this.btnCurveClearAll.Text = "🧹 Tüm Eğrileri Temizle"; + this.btnCurveClearAll.Size = new Size(284, 28); + this.btnCurveClearAll.Location = new Point(8, 300); + this.btnCurveClearAll.BackColor = Color.FromArgb(45, 55, 72); + this.btnCurveClearAll.ForeColor = Color.White; + this.btnCurveClearAll.FlatStyle = FlatStyle.Flat; + + this.tabFunctions.Controls.Add(this.lstCurves); + this.tabFunctions.Controls.Add(this.btnCurveColor); + this.tabFunctions.Controls.Add(this.cmbCurveStyle); + this.tabFunctions.Controls.Add(this.cmbCurveThickness); + this.tabFunctions.Controls.Add(this.btnCurveToggle); + this.tabFunctions.Controls.Add(this.btnCurveDelete); + this.tabFunctions.Controls.Add(this.btnCurveClearAll); + + // tabPoints + this.tabPoints.Text = "📍 Noktalar"; + this.tabPoints.BackColor = ThemeHelper.DarkBackground; + this.tabPoints.Padding = new Padding(8); + + this.lstPoints.Dock = DockStyle.Top; + this.lstPoints.Height = 180; + this.lstPoints.BackColor = Color.FromArgb(11, 17, 32); + this.lstPoints.ForeColor = Color.White; + this.lstPoints.Font = new Font("Consolas", 9.5F); + + int py = 190; + this.lblPtX.Text = "X:"; + this.lblPtX.Location = new Point(8, py + 3); + this.lblPtX.AutoSize = true; + this.lblPtX.ForeColor = ThemeHelper.LightText; + + this.txtPtX.Location = new Point(28, py); + this.txtPtX.Size = new Size(60, 24); + this.txtPtX.Text = "0"; + this.txtPtX.Font = new Font("Consolas", 9.5F); + this.txtPtX.BackColor = ThemeHelper.CardBackground; + this.txtPtX.ForeColor = Color.White; + + this.lblPtY.Text = "Y:"; + this.lblPtY.Location = new Point(95, py + 3); + this.lblPtY.AutoSize = true; + this.lblPtY.ForeColor = ThemeHelper.LightText; + + this.txtPtY.Location = new Point(115, py); + this.txtPtY.Size = new Size(60, 24); + this.txtPtY.Text = "0"; + this.txtPtY.Font = new Font("Consolas", 9.5F); + this.txtPtY.BackColor = ThemeHelper.CardBackground; + this.txtPtY.ForeColor = Color.White; + + this.btnPtColor.Text = "🎨"; + this.btnPtColor.Location = new Point(182, py); + this.btnPtColor.Size = new Size(35, 25); + this.btnPtColor.BackColor = Color.FromArgb(250, 204, 21); + this.btnPtColor.FlatStyle = FlatStyle.Flat; + + this.btnAddPoint.Text = "➕ Ekle"; + this.btnAddPoint.Location = new Point(222, py); + this.btnAddPoint.Size = new Size(70, 25); + this.btnAddPoint.BackColor = ThemeHelper.AccentBlue; + this.btnAddPoint.ForeColor = Color.White; + this.btnAddPoint.FlatStyle = FlatStyle.Flat; + + int py2 = 222; + this.lblPtShape.Text = "Şekil:"; + this.lblPtShape.Location = new Point(8, py2 + 3); + this.lblPtShape.AutoSize = true; + this.lblPtShape.ForeColor = ThemeHelper.LightText; + + this.cmbPtShape.Location = new Point(50, py2); + this.cmbPtShape.Size = new Size(125, 25); + this.cmbPtShape.DropDownStyle = ComboBoxStyle.DropDownList; + this.cmbPtShape.BackColor = ThemeHelper.CardBackground; + this.cmbPtShape.ForeColor = Color.White; + this.cmbPtShape.Items.AddRange(new object[] { "Daire", "Kare", "Çarpı", "Elmas" }); + this.cmbPtShape.SelectedIndex = 0; + + this.btnDeletePoint.Text = "🗑️ Seçiliyi Sil"; + this.btnDeletePoint.Size = new Size(138, 28); + this.btnDeletePoint.Location = new Point(8, 255); + this.btnDeletePoint.BackColor = Color.FromArgb(153, 27, 27); + this.btnDeletePoint.ForeColor = Color.White; + this.btnDeletePoint.FlatStyle = FlatStyle.Flat; + + this.btnClearPoints.Text = "🧹 Tümünü Sil"; + this.btnClearPoints.Size = new Size(138, 28); + this.btnClearPoints.Location = new Point(154, 255); + this.btnClearPoints.BackColor = Color.FromArgb(45, 55, 72); + this.btnClearPoints.ForeColor = Color.White; + this.btnClearPoints.FlatStyle = FlatStyle.Flat; + + this.lblPointHint.Text = "💡 İpucu: Grafik tuvalinde bir noktanın üzerine sağ tıklayarak da o noktayı doğrudan silebilirsiniz."; + this.lblPointHint.Location = new Point(8, 290); + this.lblPointHint.Size = new Size(284, 50); + this.lblPointHint.ForeColor = ThemeHelper.MutedText; + this.lblPointHint.Font = new Font("Segoe UI", 8.5F); + + this.tabPoints.Controls.Add(this.lstPoints); + this.tabPoints.Controls.Add(this.lblPtX); + this.tabPoints.Controls.Add(this.txtPtX); + this.tabPoints.Controls.Add(this.lblPtY); + this.tabPoints.Controls.Add(this.txtPtY); + this.tabPoints.Controls.Add(this.btnPtColor); + this.tabPoints.Controls.Add(this.btnAddPoint); + this.tabPoints.Controls.Add(this.lblPtShape); + this.tabPoints.Controls.Add(this.cmbPtShape); + this.tabPoints.Controls.Add(this.btnDeletePoint); + this.tabPoints.Controls.Add(this.btnClearPoints); + this.tabPoints.Controls.Add(this.lblPointHint); + + // tabTools + this.tabTools.Text = "🛠️ Araçlar"; + this.tabTools.BackColor = ThemeHelper.DarkBackground; + this.tabTools.Padding = new Padding(8); + + this.lblToolF1.Text = "1. Fonksiyon:"; + this.lblToolF1.Location = new Point(8, 8); + this.lblToolF1.AutoSize = true; + this.lblToolF1.ForeColor = ThemeHelper.LightText; + + this.cmbToolF1.Location = new Point(8, 28); + this.cmbToolF1.Size = new Size(284, 25); + this.cmbToolF1.DropDownStyle = ComboBoxStyle.DropDownList; + this.cmbToolF1.BackColor = ThemeHelper.CardBackground; + this.cmbToolF1.ForeColor = Color.White; + + this.lblToolF2.Text = "2. Fonksiyon:"; + this.lblToolF2.Location = new Point(8, 60); + this.lblToolF2.AutoSize = true; + this.lblToolF2.ForeColor = ThemeHelper.LightText; + + this.cmbToolF2.Location = new Point(8, 80); + this.cmbToolF2.Size = new Size(284, 25); + this.cmbToolF2.DropDownStyle = ComboBoxStyle.DropDownList; + this.cmbToolF2.BackColor = ThemeHelper.CardBackground; + this.cmbToolF2.ForeColor = Color.White; + + this.btnCommonTangent.Location = new Point(8, 115); + this.btnNearestPoints.Location = new Point(8, 150); + + this.lblToolSep.Text = "────────────────────────────"; + this.lblToolSep.Location = new Point(8, 185); + this.lblToolSep.Size = new Size(284, 16); + this.lblToolSep.ForeColor = ThemeHelper.MutedText; + + this.lblToolPointTan.Text = "Noktadan Teğet (x₀, y₀):"; + this.lblToolPointTan.Location = new Point(8, 203); + this.lblToolPointTan.AutoSize = true; + this.lblToolPointTan.ForeColor = ThemeHelper.LightText; + + this.txtTanPointX.Location = new Point(8, 225); + this.txtTanPointX.Size = new Size(70, 24); + this.txtTanPointX.Text = "0"; + this.txtTanPointX.Font = new Font("Consolas", 9.5F); + this.txtTanPointX.BackColor = ThemeHelper.CardBackground; + this.txtTanPointX.ForeColor = Color.White; + + this.txtTanPointY.Location = new Point(85, 225); + this.txtTanPointY.Size = new Size(70, 24); + this.txtTanPointY.Text = "3"; + this.txtTanPointY.Font = new Font("Consolas", 9.5F); + this.txtTanPointY.BackColor = ThemeHelper.CardBackground; + this.txtTanPointY.ForeColor = Color.White; + + this.btnPointTangent.Location = new Point(8, 255); + + this.txtToolLog.Location = new Point(8, 292); + this.txtToolLog.Size = new Size(284, 140); + this.txtToolLog.BackColor = Color.FromArgb(11, 17, 32); + this.txtToolLog.ForeColor = Color.FromArgb(226, 232, 240); + this.txtToolLog.Font = new Font("Consolas", 8.5F); + this.txtToolLog.ReadOnly = true; + + this.tabTools.Controls.Add(this.lblToolF1); + this.tabTools.Controls.Add(this.cmbToolF1); + this.tabTools.Controls.Add(this.lblToolF2); + this.tabTools.Controls.Add(this.cmbToolF2); + this.tabTools.Controls.Add(this.btnCommonTangent); + this.tabTools.Controls.Add(this.btnNearestPoints); + this.tabTools.Controls.Add(this.lblToolSep); + this.tabTools.Controls.Add(this.lblToolPointTan); + this.tabTools.Controls.Add(this.txtTanPointX); + this.tabTools.Controls.Add(this.txtTanPointY); + this.tabTools.Controls.Add(this.btnPointTangent); + this.tabTools.Controls.Add(this.txtToolLog); + + // tabShapes + this.tabShapes.Text = "📐 Şekiller"; + this.tabShapes.BackColor = ThemeHelper.DarkBackground; + this.tabShapes.Padding = new Padding(8); + + this.lblShapeType.Text = "Şekil Türü:"; + this.lblShapeType.Location = new Point(8, 12); + this.lblShapeType.AutoSize = true; + this.lblShapeType.ForeColor = ThemeHelper.LightText; + + this.cmbShapeType.Location = new Point(8, 32); + this.cmbShapeType.Size = new Size(284, 25); + this.cmbShapeType.DropDownStyle = ComboBoxStyle.DropDownList; + this.cmbShapeType.BackColor = ThemeHelper.CardBackground; + this.cmbShapeType.ForeColor = Color.White; + this.cmbShapeType.Items.AddRange(new object[] { + "Daire (Çember)", + "Kare", + "Dikdörtgen", + "Eşkenar Üçgen", + "Elips", + "Düzgün Altıgen" + }); + this.cmbShapeType.SelectedIndex = 0; + + int sy = 68; + this.lblShapeCenter.Text = "Merkez (x, y):"; + this.lblShapeCenter.Location = new Point(8, sy); + this.lblShapeCenter.AutoSize = true; + this.lblShapeCenter.ForeColor = ThemeHelper.LightText; + + this.txtShapeCenterX.Location = new Point(8, sy + 20); + this.txtShapeCenterX.Size = new Size(60, 24); + this.txtShapeCenterX.Text = "0"; + this.txtShapeCenterX.Font = new Font("Consolas", 9.5F); + this.txtShapeCenterX.BackColor = ThemeHelper.CardBackground; + this.txtShapeCenterX.ForeColor = Color.White; + + this.txtShapeCenterY.Location = new Point(75, sy + 20); + this.txtShapeCenterY.Size = new Size(60, 24); + this.txtShapeCenterY.Text = "0"; + this.txtShapeCenterY.Font = new Font("Consolas", 9.5F); + this.txtShapeCenterY.BackColor = ThemeHelper.CardBackground; + this.txtShapeCenterY.ForeColor = Color.White; + + int sy2 = 120; + this.lblShapeDim1.Text = "Yarıçap / Kenar A:"; + this.lblShapeDim1.Location = new Point(8, sy2); + this.lblShapeDim1.AutoSize = true; + this.lblShapeDim1.ForeColor = ThemeHelper.LightText; + + this.txtShapeDim1.Location = new Point(8, sy2 + 20); + this.txtShapeDim1.Size = new Size(80, 24); + this.txtShapeDim1.Text = "4"; + this.txtShapeDim1.Font = new Font("Consolas", 9.5F); + this.txtShapeDim1.BackColor = ThemeHelper.CardBackground; + this.txtShapeDim1.ForeColor = Color.White; + + this.lblShapeDim2.Text = "Yükseklik / Kenar B:"; + this.lblShapeDim2.Location = new Point(100, sy2); + this.lblShapeDim2.AutoSize = true; + this.lblShapeDim2.ForeColor = ThemeHelper.LightText; + + this.txtShapeDim2.Location = new Point(100, sy2 + 20); + this.txtShapeDim2.Size = new Size(80, 24); + this.txtShapeDim2.Text = "2"; + this.txtShapeDim2.Font = new Font("Consolas", 9.5F); + this.txtShapeDim2.BackColor = ThemeHelper.CardBackground; + this.txtShapeDim2.ForeColor = Color.White; + + this.btnAddShape.Location = new Point(8, 180); + + this.tabShapes.Controls.Add(this.lblShapeType); + this.tabShapes.Controls.Add(this.cmbShapeType); + this.tabShapes.Controls.Add(this.lblShapeCenter); + this.tabShapes.Controls.Add(this.txtShapeCenterX); + this.tabShapes.Controls.Add(this.txtShapeCenterY); + this.tabShapes.Controls.Add(this.lblShapeDim1); + this.tabShapes.Controls.Add(this.txtShapeDim1); + this.tabShapes.Controls.Add(this.lblShapeDim2); + this.tabShapes.Controls.Add(this.txtShapeDim2); + this.tabShapes.Controls.Add(this.btnAddShape); + + this.pnlRightSide.Controls.Add(this.tabManager); // pnlStatusBar this.pnlStatusBar.Dock = DockStyle.Bottom; @@ -139,7 +555,7 @@ namespace MathApp.Controls this.lblStatus.ForeColor = ThemeHelper.MutedText; this.lblStatus.Font = new Font("Segoe UI", 9F); this.lblStatus.TextAlign = ContentAlignment.MiddleLeft; - this.lblStatus.Text = "Hazır."; + this.lblStatus.Text = "Hazır. Sol tık: Nokta ekle | Sağ tık: Nokta sil | Shift+Tekerlek: X sündür | Ctrl+Tekerlek: Y sündür"; this.pnlStatusBar.Controls.Add(this.lblStatus); // pnlCanvas @@ -149,19 +565,29 @@ namespace MathApp.Controls this.pnlCanvas.Paint += new PaintEventHandler(this.pnlCanvas_Paint); this.pnlCanvas.Resize += new EventHandler(this.pnlCanvas_Resize); - // GraphPlotterControl + // Assemble GraphPlotterControl this.AutoScaleDimensions = new SizeF(7F, 15F); this.AutoScaleMode = AutoScaleMode.Font; this.BackColor = ThemeHelper.DarkBackground; this.Controls.Add(this.pnlCanvas); this.Controls.Add(this.pnlStatusBar); + this.Controls.Add(this.pnlRightSide); this.Controls.Add(this.pnlControls); this.Controls.Add(this.pnlHeader); this.Name = "GraphPlotterControl"; - this.Size = new Size(920, 660); + this.Size = new Size(1100, 720); this.pnlControls.ResumeLayout(false); this.pnlControls.PerformLayout(); + this.tabFunctions.ResumeLayout(false); + this.tabPoints.ResumeLayout(false); + this.tabPoints.PerformLayout(); + this.tabTools.ResumeLayout(false); + this.tabTools.PerformLayout(); + this.tabShapes.ResumeLayout(false); + this.tabShapes.PerformLayout(); + this.tabManager.ResumeLayout(false); + this.pnlRightSide.ResumeLayout(false); this.pnlStatusBar.ResumeLayout(false); this.ResumeLayout(false); } @@ -180,9 +606,69 @@ namespace MathApp.Controls private TextBox txtMinX; private Label lblMaxX; private TextBox txtMaxX; + private CheckBox chkClampRange; private Button btnPlot; + + private Button btnZoomXIn; + private Button btnZoomXOut; + private Button btnZoomX10; + private Button btnZoomYIn; + private Button btnZoomYOut; + private Button btnAspect1to1; private Button btnResetView; - private Button btnClearMarks; + + private Panel pnlRightSide; + private TabControl tabManager; + private TabPage tabFunctions; + private TabPage tabPoints; + private TabPage tabTools; + private TabPage tabShapes; + + private ListBox lstCurves; + private Button btnCurveColor; + private ComboBox cmbCurveStyle; + private ComboBox cmbCurveThickness; + private Button btnCurveToggle; + private Button btnCurveDelete; + private Button btnCurveClearAll; + + private ListBox lstPoints; + private Label lblPtX; + private TextBox txtPtX; + private Label lblPtY; + private TextBox txtPtY; + private Label lblPtShape; + private ComboBox cmbPtShape; + private Button btnPtColor; + private Button btnAddPoint; + private Button btnDeletePoint; + private Button btnClearPoints; + private Label lblPointHint; + + private Label lblToolF1; + private ComboBox cmbToolF1; + private Label lblToolF2; + private ComboBox cmbToolF2; + private Button btnCommonTangent; + private Button btnNearestPoints; + private Label lblToolSep; + private Label lblToolPointTan; + private TextBox txtTanPointX; + private TextBox txtTanPointY; + private Button btnPointTangent; + private RichTextBox txtToolLog; + + private Label lblShapeType; + private ComboBox cmbShapeType; + private Label lblShapeCenter; + private TextBox txtShapeCenterX; + private TextBox txtShapeCenterY; + private Label lblShapeDim1; + private TextBox txtShapeDim1; + private Label lblShapeDim2; + private TextBox txtShapeDim2; + private Button btnAddShape; + private Panel pnlStatusBar; private Label lblStatus; private Panel pnlCanvas; diff --git a/src/ttCalculator/Controls/GraphPlotterControl.cs b/src/ttCalculator/Controls/GraphPlotterControl.cs index d636d52..2429f25 100644 --- a/src/ttCalculator/Controls/GraphPlotterControl.cs +++ b/src/ttCalculator/Controls/GraphPlotterControl.cs @@ -1,25 +1,86 @@ using System; using System.Collections.Generic; using System.Drawing; +using System.Drawing.Drawing2D; using System.Globalization; +using System.Linq; using System.Reflection; +using System.Text; using System.Windows.Forms; namespace MathApp.Controls { public partial class GraphPlotterControl : UserControl { - private List> segments = new List>(); - private List markedPoints = new List(); + public enum PointShape + { + Circle, + Square, + Cross, + Diamond + } + + public class PlotPoint + { + public float X { get; set; } + public float Y { get; set; } + public Color Color { get; set; } = Color.FromArgb(250, 204, 21); + public int Size { get; set; } = 8; + public PointShape Shape { get; set; } = PointShape.Circle; + public string Label { get; set; } = ""; + + public override string ToString() => $"({X:F2}, {Y:F2}) [{Shape}]"; + } + + public class PlotCurve + { + public string Id { get; set; } = Guid.NewGuid().ToString(); + public string Equation { get; set; } + public Function Compiled { get; set; } + public Color Color { get; set; } + public float Thickness { get; set; } = 2.4f; + public DashStyle DashStyle { get; set; } = DashStyle.Solid; + public bool Visible { get; set; } = true; + public bool ClampDomain { get; set; } = false; + public float DomainMinX { get; set; } = -10f; + public float DomainMaxX { get; set; } = 10f; + public bool IsVerticalLine { get; set; } = false; + public float VerticalX { get; set; } = 0f; + public float VerticalMinY { get; set; } = 0f; + public float VerticalMaxY { get; set; } = 0f; + + public List> Segments { get; set; } = new List>(); + + public override string ToString() + { + string vis = Visible ? "✓" : "✗"; + if (IsVerticalLine) return $"{vis} [Doğru] x = {VerticalX:F2}"; + string clampStr = ClampDomain ? $" [{DomainMinX:F1}, {DomainMaxX:F1}]" : ""; + return $"{vis} y = {Equation}{clampStr}"; + } + } + + private readonly List _curves = new List(); + private readonly List _points = new List(); + + private readonly Color[] _palette = new Color[] + { + Color.FromArgb(56, 189, 248), // Sky Blue + Color.FromArgb(245, 158, 11), // Amber + Color.FromArgb(52, 211, 153), // Emerald + Color.FromArgb(244, 63, 94), // Rose + Color.FromArgb(168, 85, 247), // Violet + Color.FromArgb(236, 72, 153), // Pink + Color.FromArgb(249, 115, 22), // Orange + Color.FromArgb(20, 184, 166) // Teal + }; + private int _colorIndex = 0; private float rangeMinX = -10f; private float rangeMaxX = 10f; private float rangeMinY = -6f; private float rangeMaxY = 6f; - private string currentEq = "sin(x)"; - private Function compiledFn = null; - private bool isDragging = false; private bool didMoveMouse = false; private Point lastMousePos; @@ -35,14 +96,13 @@ namespace MathApp.Controls resampleDebounceTimer.Tick += (s, e) => { resampleDebounceTimer.Stop(); - if (!isDragging && compiledFn != null) + if (!isDragging) { - GeneratePoints(false, isDraft: false); + GenerateAllPoints(false, isDraft: false); pnlCanvas.Invalidate(); } }; - // Enable DoubleBuffering on pnlCanvas to prevent flickering during pan/zoom typeof(Panel).InvokeMember( "DoubleBuffered", BindingFlags.SetProperty | BindingFlags.Instance | BindingFlags.NonPublic, @@ -50,103 +110,402 @@ namespace MathApp.Controls pnlCanvas, new object[] { true }); - btnPlot.Click += BtnPlot_Click; - btnResetView.Click += BtnResetView_Click; - btnClearMarks.Click += (s, e) => { markedPoints.Clear(); pnlCanvas.Invalidate(); }; + SetupEvents(); - btnEx1.Click += (s, e) => LoadPreset("sin(x) * x", -10f, 10f); - btnEx2.Click += (s, e) => LoadPreset("x^3 - 3*x", -3f, 3f); - btnEx3.Click += (s, e) => LoadPreset("exp(-x^2/4)*cos(2*x)", -6f, 6f); - btnEx4.Click += (s, e) => LoadPreset("1 / (x^2 - 1)", -5f, 5f); + // Default preset + AddFunctionCurve("sin(x)", false, -10f, 10f); + } - txtEquation.KeyDown += (s, e) => { if (e.KeyCode == Keys.Enter) { e.SuppressKeyPress = true; BtnPlot_Click(this, EventArgs.Empty); } }; - txtMinX.KeyDown += (s, e) => { if (e.KeyCode == Keys.Enter) { e.SuppressKeyPress = true; BtnPlot_Click(this, EventArgs.Empty); } }; - txtMaxX.KeyDown += (s, e) => { if (e.KeyCode == Keys.Enter) { e.SuppressKeyPress = true; BtnPlot_Click(this, EventArgs.Empty); } }; + private void SetupEvents() + { + btnPlot.Click += (s, e) => AddCurrentInputCurve(); + txtEquation.KeyDown += (s, e) => { if (e.KeyCode == Keys.Enter) { e.SuppressKeyPress = true; AddCurrentInputCurve(); } }; + txtMinX.KeyDown += (s, e) => { if (e.KeyCode == Keys.Enter) { e.SuppressKeyPress = true; AddCurrentInputCurve(); } }; + txtMaxX.KeyDown += (s, e) => { if (e.KeyCode == Keys.Enter) { e.SuppressKeyPress = true; AddCurrentInputCurve(); } }; + // Presets + btnEx1.Click += (s, e) => { txtEquation.Text = "sin(x) * x"; AddCurrentInputCurve(); }; + btnEx2.Click += (s, e) => { txtEquation.Text = "x^3 - 3*x"; AddCurrentInputCurve(); }; + btnEx3.Click += (s, e) => { txtEquation.Text = "exp(-x^2/4)*cos(2*x)"; AddCurrentInputCurve(); }; + btnEx4.Click += (s, e) => { txtEquation.Text = "1 / (x^2 - 1)"; AddCurrentInputCurve(); }; + + // Scaling & Zoom toolbar + btnZoomXIn.Click += (s, e) => ScaleAxisX(0.7f); + btnZoomXOut.Click += (s, e) => ScaleAxisX(1.4f); + btnZoomX10.Click += (s, e) => ScaleAxisX(0.1f); + btnZoomYIn.Click += (s, e) => ScaleAxisY(0.7f); + btnZoomYOut.Click += (s, e) => ScaleAxisY(1.4f); + btnAspect1to1.Click += (s, e) => LockAspect1to1(); + btnResetView.Click += (s, e) => ResetView(); + + // Canvas Mouse Events pnlCanvas.MouseDown += PnlCanvas_MouseDown; pnlCanvas.MouseMove += PnlCanvas_MouseMove; pnlCanvas.MouseUp += PnlCanvas_MouseUp; pnlCanvas.MouseLeave += (s, e) => { hoverMousePos = null; pnlCanvas.Invalidate(); }; pnlCanvas.MouseWheel += PnlCanvas_MouseWheel; - // Plot default function on startup - PlotNewEquation(true); - } + // Curve management + lstCurves.SelectedIndexChanged += LstCurves_SelectedIndexChanged; + btnCurveColor.Click += BtnCurveColor_Click; + cmbCurveStyle.SelectedIndexChanged += CmbCurveStyle_SelectedIndexChanged; + cmbCurveThickness.SelectedIndexChanged += CmbCurveThickness_SelectedIndexChanged; + btnCurveToggle.Click += BtnCurveToggle_Click; + btnCurveDelete.Click += BtnCurveDelete_Click; + btnCurveClearAll.Click += BtnCurveClearAll_Click; - private void LoadPreset(string eq, float minX, float maxX) - { - txtEquation.Text = eq; - txtMinX.Text = minX.ToString(CultureInfo.InvariantCulture); - txtMaxX.Text = maxX.ToString(CultureInfo.InvariantCulture); - PlotNewEquation(true); - } - - private void BtnPlot_Click(object sender, EventArgs e) - { - PlotNewEquation(true); - } - - private void BtnResetView_Click(object sender, EventArgs e) - { - txtMinX.Text = "-10"; - txtMaxX.Text = "10"; - PlotNewEquation(true); - } - - private void PlotNewEquation(bool autoFitY) - { - currentEq = txtEquation.Text.Trim(); - if (string.IsNullOrWhiteSpace(currentEq)) return; - - rangeMinX = ParseFloat(txtMinX.Text, -10f); - rangeMaxX = ParseFloat(txtMaxX.Text, 10f); - if (rangeMinX >= rangeMaxX) + // Point management + btnAddPoint.Click += BtnAddPoint_Click; + btnDeletePoint.Click += BtnDeletePoint_Click; + btnClearPoints.Click += (s, e) => { _points.Clear(); RefreshPointsList(); pnlCanvas.Invalidate(); }; + btnPtColor.Click += (s, e) => { - rangeMinX = -10f; - rangeMaxX = 10f; - } + using (ColorDialog cd = new ColorDialog()) + { + cd.Color = btnPtColor.BackColor; + if (cd.ShowDialog() == DialogResult.OK) + { + btnPtColor.BackColor = cd.Color; + } + } + }; - try - { - compiledFn = NumericalMethods.CompileFunction(currentEq); - lblStatus.Text = $"✓ Çizildi: y = {currentEq} | Sol Tık + Sürükle: Kaydır | Tekerlek: Yakınlaştır | Tıkla: Nokta İşaretle"; - lblStatus.ForeColor = ThemeHelper.MutedText; - } - catch (Exception ex) - { - compiledFn = null; - segments.Clear(); - lblStatus.Text = "❌ Denklem Hatası: " + ex.Message; - lblStatus.ForeColor = ThemeHelper.DangerRed; - pnlCanvas.Invalidate(); - return; - } + // Tools Tab + btnCommonTangent.Click += BtnCommonTangent_Click; + btnNearestPoints.Click += BtnNearestPoints_Click; + btnPointTangent.Click += BtnPointTangent_Click; - GeneratePoints(autoFitY); + // Shapes Tab + btnAddShape.Click += BtnAddShape_Click; + } + + #region Scaling & Zooming + + private void ScaleAxisX(float factor) + { + float midX = (rangeMaxX + rangeMinX) / 2f; + float halfW = ((rangeMaxX - rangeMinX) * factor) / 2f; + if (halfW < 1e-4f || halfW > 1e6f) return; + + rangeMinX = midX - halfW; + rangeMaxX = midX + halfW; + txtMinX.Text = rangeMinX.ToString("0.##", CultureInfo.InvariantCulture); + txtMaxX.Text = rangeMaxX.ToString("0.##", CultureInfo.InvariantCulture); + + GenerateAllPoints(false); pnlCanvas.Invalidate(); } - private float ParseFloat(string s, float def) + private void ScaleAxisY(float factor) { - string norm = (s ?? "").Trim().Replace(',', '.'); - if (float.TryParse(norm, NumberStyles.Any, CultureInfo.InvariantCulture, out float v)) return v; - return def; + float midY = (rangeMaxY + rangeMinY) / 2f; + float halfH = ((rangeMaxY - rangeMinY) * factor) / 2f; + if (halfH < 1e-4f || halfH > 1e6f) return; + + rangeMinY = midY - halfH; + rangeMaxY = midY + halfH; + + GenerateAllPoints(false); + pnlCanvas.Invalidate(); } - private void GeneratePoints(bool autoFitY, bool isDraft = false) + private void LockAspect1to1() { - segments.Clear(); - if (compiledFn == null) return; + float rangeW = rangeMaxX - rangeMinX; + float w = Math.Max(1, pnlCanvas.Width); + float h = Math.Max(1, pnlCanvas.Height); - int sampleCount = isDraft - ? Math.Min(220, Math.Max(120, pnlCanvas.Width / 3)) - : Math.Max(600, pnlCanvas.Width * 2); - float step = (rangeMaxX - rangeMinX) / sampleCount; + float targetH = rangeW * (h / w); + float midY = (rangeMaxY + rangeMinY) / 2f; + rangeMinY = midY - targetH / 2f; + rangeMaxY = midY + targetH / 2f; + + GenerateAllPoints(false); + pnlCanvas.Invalidate(); + lblStatus.Text = "Eksen oranları 1:1 olarak eşitlendi."; + } + + private void ResetView() + { + rangeMinX = -10f; + rangeMaxX = 10f; + rangeMinY = -6f; + rangeMaxY = 6f; + txtMinX.Text = "-10"; + txtMaxX.Text = "10"; + GenerateAllPoints(false); + pnlCanvas.Invalidate(); + } + + #endregion + + #region Curve Management + + private void AddCurrentInputCurve() + { + string eq = txtEquation.Text.Trim(); + if (string.IsNullOrWhiteSpace(eq)) return; + + float minX = ParseFloat(txtMinX.Text, -10f); + float maxX = ParseFloat(txtMaxX.Text, 10f); + if (minX >= maxX) { minX = -10f; maxX = 10f; } + + bool clamp = chkClampRange.Checked; + AddFunctionCurve(eq, clamp, minX, maxX); + } + + public void AddFunctionCurve(string eq, bool clamp, float minX, float maxX, Color? color = null, DashStyle dash = DashStyle.Solid, float thickness = 2.4f) + { + try + { + Function fn = NumericalMethods.CompileFunction(eq); + Color c = color ?? _palette[_colorIndex % _palette.Length]; + _colorIndex++; + + var curve = new PlotCurve + { + Equation = eq, + Compiled = fn, + Color = c, + Thickness = thickness, + DashStyle = dash, + Visible = true, + ClampDomain = clamp, + DomainMinX = minX, + DomainMaxX = maxX + }; + + _curves.Add(curve); + RefreshCurvesList(); + RefreshToolCombos(); + + GenerateCurveSegments(curve, isDraft: false); + pnlCanvas.Invalidate(); + + lblStatus.Text = $"✓ Eğri eklendi: y = {eq}"; + lblStatus.ForeColor = Color.FromArgb(52, 211, 153); + } + catch (Exception ex) + { + MessageBox.Show($"Fonksiyon derlenemedi:\n{ex.Message}", "Formül Hatası", MessageBoxButtons.OK, MessageBoxIcon.Warning); + lblStatus.Text = "❌ Hata: " + ex.Message; + lblStatus.ForeColor = ThemeHelper.DangerRed; + } + } + + public void AddVerticalLine(float x, float minY, float maxY, Color color, DashStyle dash = DashStyle.Solid, float thickness = 2f) + { + var curve = new PlotCurve + { + IsVerticalLine = true, + VerticalX = x, + VerticalMinY = minY, + VerticalMaxY = maxY, + Color = color, + Thickness = thickness, + DashStyle = dash, + Visible = true + }; + _curves.Add(curve); + RefreshCurvesList(); + RefreshToolCombos(); + pnlCanvas.Invalidate(); + } + + private void RefreshCurvesList() + { + lstCurves.BeginUpdate(); + lstCurves.Items.Clear(); + foreach (var c in _curves) + { + lstCurves.Items.Add(c); + } + lstCurves.EndUpdate(); + if (_curves.Count > 0 && lstCurves.SelectedIndex < 0) + lstCurves.SelectedIndex = _curves.Count - 1; + } + + private void RefreshToolCombos() + { + var validCurves = _curves.Where(c => !c.IsVerticalLine).ToList(); + + cmbToolF1.Items.Clear(); + cmbToolF2.Items.Clear(); + + foreach (var c in validCurves) + { + cmbToolF1.Items.Add(c.Equation); + cmbToolF2.Items.Add(c.Equation); + } + + if (cmbToolF1.Items.Count > 0) cmbToolF1.SelectedIndex = 0; + if (cmbToolF2.Items.Count > 1) cmbToolF2.SelectedIndex = 1; + else if (cmbToolF2.Items.Count > 0) cmbToolF2.SelectedIndex = 0; + } + + private void LstCurves_SelectedIndexChanged(object sender, EventArgs e) + { + if (lstCurves.SelectedItem is PlotCurve c) + { + btnCurveColor.BackColor = c.Color; + if (c.DashStyle == DashStyle.Solid) cmbCurveStyle.SelectedIndex = 0; + else if (c.DashStyle == DashStyle.Dash) cmbCurveStyle.SelectedIndex = 1; + else cmbCurveStyle.SelectedIndex = 2; + + if (c.Thickness <= 1.2f) cmbCurveThickness.SelectedIndex = 0; + else if (c.Thickness <= 2.2f) cmbCurveThickness.SelectedIndex = 1; + else if (c.Thickness <= 3.2f) cmbCurveThickness.SelectedIndex = 2; + else cmbCurveThickness.SelectedIndex = 3; + } + } + + private void BtnCurveColor_Click(object sender, EventArgs e) + { + if (lstCurves.SelectedItem is PlotCurve c) + { + using (ColorDialog cd = new ColorDialog()) + { + cd.Color = c.Color; + if (cd.ShowDialog() == DialogResult.OK) + { + c.Color = cd.Color; + btnCurveColor.BackColor = cd.Color; + pnlCanvas.Invalidate(); + } + } + } + } + + private void CmbCurveStyle_SelectedIndexChanged(object sender, EventArgs e) + { + if (lstCurves.SelectedItem is PlotCurve c) + { + if (cmbCurveStyle.SelectedIndex == 0) c.DashStyle = DashStyle.Solid; + else if (cmbCurveStyle.SelectedIndex == 1) c.DashStyle = DashStyle.Dash; + else c.DashStyle = DashStyle.Dot; + pnlCanvas.Invalidate(); + } + } + + private void CmbCurveThickness_SelectedIndexChanged(object sender, EventArgs e) + { + if (lstCurves.SelectedItem is PlotCurve c) + { + c.Thickness = (cmbCurveThickness.SelectedIndex + 1) * 1.2f; + pnlCanvas.Invalidate(); + } + } + + private void BtnCurveToggle_Click(object sender, EventArgs e) + { + if (lstCurves.SelectedItem is PlotCurve c) + { + c.Visible = !c.Visible; + int idx = lstCurves.SelectedIndex; + RefreshCurvesList(); + lstCurves.SelectedIndex = idx; + pnlCanvas.Invalidate(); + } + } + + private void BtnCurveDelete_Click(object sender, EventArgs e) + { + if (lstCurves.SelectedItem is PlotCurve c) + { + _curves.Remove(c); + RefreshCurvesList(); + RefreshToolCombos(); + pnlCanvas.Invalidate(); + } + } + + private void BtnCurveClearAll_Click(object sender, EventArgs e) + { + _curves.Clear(); + RefreshCurvesList(); + RefreshToolCombos(); + pnlCanvas.Invalidate(); + } + + #endregion + + #region Point Management + + private void RefreshPointsList() + { + lstPoints.BeginUpdate(); + lstPoints.Items.Clear(); + foreach (var p in _points) + { + lstPoints.Items.Add(p); + } + lstPoints.EndUpdate(); + if (_points.Count > 0 && lstPoints.SelectedIndex < 0) + lstPoints.SelectedIndex = _points.Count - 1; + } + + private void BtnAddPoint_Click(object sender, EventArgs e) + { + float px = ParseFloat(txtPtX.Text, 0f); + float py = ParseFloat(txtPtY.Text, 0f); + + PointShape shape = (PointShape)Math.Max(0, cmbPtShape.SelectedIndex); + _points.Add(new PlotPoint + { + X = px, + Y = py, + Color = btnPtColor.BackColor, + Shape = shape, + Size = 8 + }); + + RefreshPointsList(); + pnlCanvas.Invalidate(); + lblStatus.Text = $"Nokta eklendi: ({px:F2}, {py:F2})"; + } + + private void BtnDeletePoint_Click(object sender, EventArgs e) + { + if (lstPoints.SelectedItem is PlotPoint p) + { + _points.Remove(p); + RefreshPointsList(); + pnlCanvas.Invalidate(); + lblStatus.Text = "Nokta silindi."; + } + } + + #endregion + + #region Point Generation & Segment Caching + + private void GenerateAllPoints(bool autoFitY, bool isDraft = false) + { + foreach (var c in _curves) + { + if (c.Visible && !c.IsVerticalLine && c.Compiled != null) + { + GenerateCurveSegments(c, isDraft); + } + } + } + + private void GenerateCurveSegments(PlotCurve curve, bool isDraft = false) + { + curve.Segments.Clear(); + if (curve.Compiled == null) return; + + float drawMinX = curve.ClampDomain ? Math.Max(rangeMinX, curve.DomainMinX) : rangeMinX; + float drawMaxX = curve.ClampDomain ? Math.Min(rangeMaxX, curve.DomainMaxX) : rangeMaxX; + if (drawMinX >= drawMaxX) return; + + int sampleCount = isDraft + ? Math.Min(200, Math.Max(100, pnlCanvas.Width / 3)) + : Math.Max(500, pnlCanvas.Width * 2); + + float step = (drawMaxX - drawMinX) / sampleCount; if (step <= 0) return; - float tempMinY = float.MaxValue; - float tempMaxY = float.MinValue; - List currentSegment = new List(); float? prevY = null; @@ -156,39 +515,33 @@ namespace MathApp.Controls { for (int i = 0; i <= sampleCount; i++) { - float x = rangeMinX + i * step; + float x = drawMinX + i * step; try { - decimal val = NumericalMethods.EvaluateCompiled(compiledFn, "x", (decimal)x); + decimal val = NumericalMethods.EvaluateCompiled(curve.Compiled, "x", (decimal)x); float y = (float)val; if (float.IsNaN(y) || float.IsInfinity(y) || Math.Abs(y) > 1e6f) { - if (currentSegment.Count > 1) segments.Add(currentSegment); + if (currentSegment.Count > 1) curve.Segments.Add(currentSegment); currentSegment = new List(); prevY = null; continue; } - // Detect vertical asymptote jump (e.g. 1/x or tan(x)) + // Asymptote jump filter if (prevY.HasValue && Math.Abs(y - prevY.Value) > (rangeMaxY - rangeMinY) * 2.5f && (y * prevY.Value < 0)) { - if (currentSegment.Count > 1) segments.Add(currentSegment); + if (currentSegment.Count > 1) curve.Segments.Add(currentSegment); currentSegment = new List(); } currentSegment.Add(new PointF(x, y)); prevY = y; - - if (Math.Abs(y) < 500f) - { - if (y < tempMinY) tempMinY = y; - if (y > tempMaxY) tempMaxY = y; - } } catch { - if (currentSegment.Count > 1) segments.Add(currentSegment); + if (currentSegment.Count > 1) curve.Segments.Add(currentSegment); currentSegment = new List(); prevY = null; } @@ -201,30 +554,32 @@ namespace MathApp.Controls if (currentSegment.Count > 1) { - segments.Add(currentSegment); - } - - if (autoFitY) - { - if (tempMinY < tempMaxY) - { - float h = tempMaxY - tempMinY; - if (h < 1e-3f) h = 4f; - rangeMinY = tempMinY - h * 0.18f; - rangeMaxY = tempMaxY + h * 0.18f; - } - else - { - rangeMinY = -10f; - rangeMaxY = 10f; - } + curve.Segments.Add(currentSegment); } } + #endregion + + #region Mouse Canvas Handlers + private void PnlCanvas_MouseWheel(object sender, MouseEventArgs e) { float zoom = (e.Delta > 0) ? 0.85f : 1.18f; + bool shift = (Control.ModifierKeys & Keys.Shift) == Keys.Shift; + bool ctrl = (Control.ModifierKeys & Keys.Control) == Keys.Control; + + if (shift) + { + ScaleAxisX(zoom); + return; + } + if (ctrl) + { + ScaleAxisY(zoom); + return; + } + float rangeW = rangeMaxX - rangeMinX; float rangeH = rangeMaxY - rangeMinY; if (rangeW < 1e-4f && zoom < 1f) return; @@ -233,19 +588,15 @@ namespace MathApp.Controls float midX = (rangeMaxX + rangeMinX) / 2f; float midY = (rangeMaxY + rangeMinY) / 2f; - float halfW = (rangeW * zoom) / 2f; - float halfH = (rangeH * zoom) / 2f; - - rangeMinX = midX - halfW; - rangeMaxX = midX + halfW; - rangeMinY = midY - halfH; - rangeMaxY = midY + halfH; + rangeMinX = midX - (rangeW * zoom) / 2f; + rangeMaxX = midX + (rangeW * zoom) / 2f; + rangeMinY = midY - (rangeH * zoom) / 2f; + rangeMaxY = midY + (rangeH * zoom) / 2f; txtMinX.Text = rangeMinX.ToString("0.##", CultureInfo.InvariantCulture); txtMaxX.Text = rangeMaxX.ToString("0.##", CultureInfo.InvariantCulture); - // Fast preview during continuous wheel spin, debounce high-res - GeneratePoints(false, isDraft: true); + GenerateAllPoints(false, isDraft: true); resampleDebounceTimer.Stop(); resampleDebounceTimer.Start(); pnlCanvas.Invalidate(); @@ -254,6 +605,38 @@ namespace MathApp.Controls private void PnlCanvas_MouseDown(object sender, MouseEventArgs e) { pnlCanvas.Focus(); + + if (e.Button == MouseButtons.Right) + { + // Requirement 1: Right-click deletes individual point! + float w = Math.Max(1, pnlCanvas.Width); + float h = Math.Max(1, pnlCanvas.Height); + float MapX(float x) => (x - rangeMinX) / (rangeMaxX - rangeMinX) * w; + float MapY(float y) => h - ((y - rangeMinY) / (rangeMaxY - rangeMinY) * h); + + PlotPoint toRemove = null; + for (int i = _points.Count - 1; i >= 0; i--) + { + var p = _points[i]; + float sx = MapX(p.X); + float sy = MapY(p.Y); + if (Math.Abs(sx - e.X) < 14 && Math.Abs(sy - e.Y) < 14) + { + toRemove = p; + break; + } + } + + if (toRemove != null) + { + _points.Remove(toRemove); + RefreshPointsList(); + pnlCanvas.Invalidate(); + lblStatus.Text = $"Nokta silindi: ({toRemove.X:F2}, {toRemove.Y:F2})"; + } + return; + } + if (e.Button == MouseButtons.Left) { isDragging = true; @@ -271,14 +654,10 @@ namespace MathApp.Controls int dx = e.X - lastMousePos.X; int dy = e.Y - lastMousePos.Y; - if (Math.Abs(dx) > 2 || Math.Abs(dy) > 2) - { - didMoveMouse = true; - } + if (Math.Abs(dx) > 2 || Math.Abs(dy) > 2) didMoveMouse = true; float rangeW = rangeMaxX - rangeMinX; float rangeH = rangeMaxY - rangeMinY; - float w = Math.Max(1, pnlCanvas.Width); float h = Math.Max(1, pnlCanvas.Height); @@ -294,15 +673,13 @@ namespace MathApp.Controls txtMaxX.Text = rangeMaxX.ToString("0.##", CultureInfo.InvariantCulture); lastMousePos = e.Location; - // Fluid high-FPS drag preview - GeneratePoints(false, isDraft: true); + GenerateAllPoints(false, isDraft: true); resampleDebounceTimer.Stop(); resampleDebounceTimer.Start(); pnlCanvas.Invalidate(); } else { - // Throttle hover redraws: only repaint when moved at least 2 pixels if (Math.Abs(e.X - lastHoverRecorded.X) >= 2 || Math.Abs(e.Y - lastHoverRecorded.Y) >= 2) { lastHoverRecorded = e.Location; @@ -316,45 +693,71 @@ namespace MathApp.Controls { if (e.Button == MouseButtons.Left) { - if (!didMoveMouse && compiledFn != null) + if (!didMoveMouse) { - // Snap marked point onto the function curve at clicked X! + // Snap point onto active curve or clicked coordinate float w = Math.Max(1, pnlCanvas.Width); + float h = Math.Max(1, pnlCanvas.Height); float xPct = e.X / w; float logX = rangeMinX + xPct * (rangeMaxX - rangeMinX); - bool prevRad = Function.UseRadians; - Function.UseRadians = true; - try + var activeCurve = _curves.FirstOrDefault(c => c.Visible && !c.IsVerticalLine && c.Compiled != null); + float logY; + + if (activeCurve != null) { - decimal fx = NumericalMethods.EvaluateCompiled(compiledFn, "x", (decimal)logX); - markedPoints.Add(new PointF(logX, (float)fx)); + bool prevRad = Function.UseRadians; + Function.UseRadians = true; + try + { + decimal fx = NumericalMethods.EvaluateCompiled(activeCurve.Compiled, "x", (decimal)logX); + logY = (float)fx; + } + catch + { + float yPct = (h - e.Y) / h; + logY = rangeMinY + yPct * (rangeMaxY - rangeMinY); + } + finally + { + Function.UseRadians = prevRad; + } } - catch + else { - float h = Math.Max(1, pnlCanvas.Height); float yPct = (h - e.Y) / h; - float logY = rangeMinY + yPct * (rangeMaxY - rangeMinY); - markedPoints.Add(new PointF(logX, logY)); + logY = rangeMinY + yPct * (rangeMaxY - rangeMinY); } - finally + + _points.Add(new PlotPoint { - Function.UseRadians = prevRad; - } + X = logX, + Y = logY, + Color = btnPtColor.BackColor, + Shape = (PointShape)Math.Max(0, cmbPtShape.SelectedIndex), + Size = 8 + }); + + RefreshPointsList(); + lblStatus.Text = $"Nokta eklendi: ({logX:F2}, {logY:F2}) - Silmek için sağ tıklayın."; } isDragging = false; resampleDebounceTimer.Stop(); - GeneratePoints(false, isDraft: false); + GenerateAllPoints(false, isDraft: false); Cursor = Cursors.Cross; pnlCanvas.Invalidate(); } } + #endregion + + #region Rendering (Paint) + private void pnlCanvas_Paint(object sender, PaintEventArgs e) { Graphics g = e.Graphics; - g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; + g.SmoothingMode = SmoothingMode.AntiAlias; g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit; float w = Math.Max(1, pnlCanvas.Width); @@ -363,10 +766,10 @@ namespace MathApp.Controls float MapX(float x) => (x - rangeMinX) / (rangeMaxX - rangeMinX) * w; float MapY(float y) => h - ((y - rangeMinY) / (rangeMaxY - rangeMinY) * h); - // 1. Draw Grid + // 1. Grid DrawGrid(g, w, h, MapX, MapY); - // 2. Draw Axes + // 2. Axes using (Pen axisPen = new Pen(Color.FromArgb(148, 163, 184), 1.8f)) { float y0 = MapY(0); @@ -376,101 +779,158 @@ namespace MathApp.Controls if (x0 >= 0 && x0 <= w) g.DrawLine(axisPen, x0, 0, x0, h); } - // 3. Draw Function Curve Segments - if (segments.Count > 0) + // 3. Draw Curves + foreach (var curve in _curves) { - using (Pen glowPen = new Pen(Color.FromArgb(45, 56, 189, 248), 6f)) - using (Pen graphPen = new Pen(Color.FromArgb(56, 189, 248), 2.4f)) + if (!curve.Visible) continue; + + if (curve.IsVerticalLine) { - foreach (var seg in segments) + float sx = MapX(curve.VerticalX); + float sy1 = MapY(curve.VerticalMinY); + float sy2 = MapY(curve.VerticalMaxY); + using (Pen p = new Pen(curve.Color, curve.Thickness) { DashStyle = curve.DashStyle }) + { + g.DrawLine(p, sx, sy1, sx, sy2); + } + continue; + } + + using (Pen glowPen = new Pen(Color.FromArgb(40, curve.Color), curve.Thickness + 4f)) + using (Pen linePen = new Pen(curve.Color, curve.Thickness) { DashStyle = curve.DashStyle }) + { + foreach (var seg in curve.Segments) { if (seg.Count < 2) continue; - List screenPoints = new List(seg.Count); + List screenPts = new List(seg.Count); foreach (var p in seg) { float sx = MapX(p.X); float sy = MapY(p.Y); if (sy < -5000f) sy = -5000f; if (sy > h + 5000f) sy = h + 5000f; - screenPoints.Add(new PointF(sx, sy)); + screenPts.Add(new PointF(sx, sy)); } try { - PointF[] arr = screenPoints.ToArray(); + PointF[] arr = screenPts.ToArray(); g.DrawLines(glowPen, arr); - g.DrawLines(graphPen, arr); + g.DrawLines(linePen, arr); } catch { } } } } - // 4. Draw Live Hover Crosshair & f(x) Value - if (hoverMousePos.HasValue && !isDragging && compiledFn != null) - { - float mx = hoverMousePos.Value.X; - float logX = rangeMinX + (mx / w) * (rangeMaxX - rangeMinX); - - bool prevRad = Function.UseRadians; - Function.UseRadians = true; - try - { - decimal fxDec = NumericalMethods.EvaluateCompiled(compiledFn, "x", (decimal)logX); - float logY = (float)fxDec; - float sy = MapY(logY); - - using (Pen dashPen = new Pen(Color.FromArgb(90, 248, 250, 252), 1f)) - { - dashPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash; - g.DrawLine(dashPen, mx, 0, mx, h); - if (sy >= 0 && sy <= h) - { - g.DrawLine(dashPen, 0, sy, w, sy); - using (Brush dotBrush = new SolidBrush(Color.FromArgb(56, 189, 248))) - { - g.FillEllipse(dotBrush, mx - 4, sy - 4, 8, 8); - } - } - } - - string coordInfo = $"x = {logX:F3} | f(x) = {logY:F4}"; - using (Font hudFont = new Font("Consolas", 9.5F, FontStyle.Bold)) - using (Brush hudBg = new SolidBrush(Color.FromArgb(210, 15, 23, 42))) - using (Brush hudFg = new SolidBrush(Color.FromArgb(186, 230, 253))) - { - SizeF sz = g.MeasureString(coordInfo, hudFont); - RectangleF rect = new RectangleF(w - sz.Width - 24, 12, sz.Width + 12, sz.Height + 8); - g.FillRectangle(hudBg, rect); - g.DrawString(coordInfo, hudFont, hudFg, rect.X + 6, rect.Y + 4); - } - } - catch { } - finally - { - Function.UseRadians = prevRad; - } - } - - // 5. Draw Marked Points - using (Brush markBrush = new SolidBrush(Color.FromArgb(250, 204, 21))) + // 4. Draw Marked Points + using (Font markFont = new Font("Consolas", 8.5F, FontStyle.Bold)) using (Brush bgTag = new SolidBrush(Color.FromArgb(200, 15, 23, 42))) - using (Pen markPen = new Pen(Color.FromArgb(244, 63, 94), 2.2f)) - using (Font markFont = new Font("Consolas", 9F, FontStyle.Bold)) { - foreach (var p in markedPoints) + foreach (var p in _points) { float sx = MapX(p.X); float sy = MapY(p.Y); if (sx < -50 || sx > w + 50 || sy < -50 || sy > h + 50) continue; - g.FillEllipse(markBrush, sx - 4, sy - 4, 8, 8); - g.DrawEllipse(markPen, sx - 6, sy - 6, 12, 12); + DrawCustomPoint(g, sx, sy, p); string coord = $"({p.X:F2}, {p.Y:F2})"; SizeF sz = g.MeasureString(coord, markFont); - g.FillRectangle(bgTag, sx + 8, sy - 22, sz.Width + 4, sz.Height + 2); - g.DrawString(coord, markFont, markBrush, sx + 10, sy - 21); + g.FillRectangle(bgTag, sx + 8, sy - 20, sz.Width + 4, sz.Height + 2); + using (Brush textBr = new SolidBrush(p.Color)) + { + g.DrawString(coord, markFont, textBr, sx + 10, sy - 19); + } + } + } + + // 5. Live Hover Coordinate HUD + if (hoverMousePos.HasValue && !isDragging) + { + float mx = hoverMousePos.Value.X; + float logX = rangeMinX + (mx / w) * (rangeMaxX - rangeMinX); + + var activeCurve = _curves.FirstOrDefault(c => c.Visible && !c.IsVerticalLine && c.Compiled != null); + if (activeCurve != null) + { + bool prevRad = Function.UseRadians; + Function.UseRadians = true; + try + { + decimal fxDec = NumericalMethods.EvaluateCompiled(activeCurve.Compiled, "x", (decimal)logX); + float logY = (float)fxDec; + float sy = MapY(logY); + + using (Pen dashPen = new Pen(Color.FromArgb(90, 248, 250, 252), 1f) { DashStyle = DashStyle.Dash }) + { + g.DrawLine(dashPen, mx, 0, mx, h); + if (sy >= 0 && sy <= h) + { + g.DrawLine(dashPen, 0, sy, w, sy); + using (Brush dotBrush = new SolidBrush(activeCurve.Color)) + { + g.FillEllipse(dotBrush, mx - 4, sy - 4, 8, 8); + } + } + } + + string coordInfo = $"x = {logX:F3} | f(x) = {logY:F4} ({activeCurve.Equation})"; + using (Font hudFont = new Font("Consolas", 9F, FontStyle.Bold)) + using (Brush hudBg = new SolidBrush(Color.FromArgb(220, 15, 23, 42))) + using (Brush hudFg = new SolidBrush(Color.FromArgb(186, 230, 253))) + { + SizeF sz = g.MeasureString(coordInfo, hudFont); + RectangleF rect = new RectangleF(16, 12, sz.Width + 12, sz.Height + 8); + g.FillRectangle(hudBg, rect); + g.DrawString(coordInfo, hudFont, hudFg, rect.X + 6, rect.Y + 4); + } + } + catch { } + finally { Function.UseRadians = prevRad; } + } + } + } + + private void DrawCustomPoint(Graphics g, float sx, float sy, PlotPoint p) + { + int sz = p.Size; + float half = sz / 2f; + using (Brush b = new SolidBrush(p.Color)) + using (Pen pen = new Pen(Color.White, 1.5f)) + { + switch (p.Shape) + { + case PointShape.Square: + g.FillRectangle(b, sx - half, sy - half, sz, sz); + g.DrawRectangle(pen, sx - half, sy - half, sz, sz); + break; + + case PointShape.Diamond: + PointF[] diamond = new PointF[] + { + new PointF(sx, sy - half - 1), + new PointF(sx + half + 1, sy), + new PointF(sx, sy + half + 1), + new PointF(sx - half - 1, sy) + }; + g.FillPolygon(b, diamond); + g.DrawPolygon(pen, diamond); + break; + + case PointShape.Cross: + using (Pen thickPen = new Pen(p.Color, 2.5f)) + { + g.DrawLine(thickPen, sx - half, sy - half, sx + half, sy + half); + g.DrawLine(thickPen, sx - half, sy + half, sx + half, sy - half); + } + break; + + case PointShape.Circle: + default: + g.FillEllipse(b, sx - half, sy - half, sz, sz); + g.DrawEllipse(pen, sx - half - 1, sy - half - 1, sz + 2, sz + 2); + break; } } } @@ -526,7 +986,403 @@ namespace MathApp.Controls private void pnlCanvas_Resize(object sender, EventArgs e) { + GenerateAllPoints(false, isDraft: false); pnlCanvas.Invalidate(); } + + private float ParseFloat(string s, float def) + { + string norm = (s ?? "").Trim().Replace(',', '.'); + if (float.TryParse(norm, NumberStyles.Any, CultureInfo.InvariantCulture, out float v)) return v; + return def; + } + + #endregion + + #region Advanced Tools (Common Tangent, Closest Points, Tangent from Point) + + private void BtnCommonTangent_Click(object sender, EventArgs e) + { + string eq1 = cmbToolF1.SelectedItem?.ToString(); + string eq2 = cmbToolF2.SelectedItem?.ToString(); + + if (string.IsNullOrWhiteSpace(eq1) || string.IsNullOrWhiteSpace(eq2)) + { + MessageBox.Show("Lütfen araç için listeden iki fonksiyon seçin.", "Seçim Eksik", MessageBoxButtons.OK, MessageBoxIcon.Information); + return; + } + + try + { + Function f1 = NumericalMethods.CompileFunction(eq1); + Function f2 = NumericalMethods.CompileFunction(eq2); + + decimal EvalF1(decimal x) => NumericalMethods.EvaluateCompiled(f1, "x", x); + decimal EvalF2(decimal x) => NumericalMethods.EvaluateCompiled(f2, "x", x); + decimal DerivF1(decimal x) => EvalDeriv(f1, x); + decimal DerivF2(decimal x) => EvalDeriv(f2, x); + + // Scan grid over [rangeMinX, rangeMaxX] for (x1, x2) minimizing common tangent loss + decimal bestLoss = decimal.MaxValue; + decimal bestX1 = 0m, bestX2 = 0m; + + int gridN = 40; + decimal xStart = (decimal)rangeMinX; + decimal xEnd = (decimal)rangeMaxX; + decimal dx = (xEnd - xStart) / gridN; + + for (int i = 0; i <= gridN; i++) + { + decimal x1 = xStart + i * dx; + decimal m1 = DerivF1(x1); + decimal y1 = EvalF1(x1); + + for (int j = 0; j <= gridN; j++) + { + decimal x2 = xStart + j * dx; + if (DecimalMath.Abs(x1 - x2) < 0.05m) continue; + + decimal m2 = DerivF2(x2); + decimal y2 = EvalF2(x2); + decimal chordSlope = (y2 - y1) / (x2 - x1); + + decimal loss = (m1 - m2) * (m1 - m2) + (chordSlope - m1) * (chordSlope - m1); + if (loss < bestLoss) + { + bestLoss = loss; + bestX1 = x1; + bestX2 = x2; + } + } + } + + if (bestLoss < 1.0m) + { + decimal m = DerivF1(bestX1); + decimal c = EvalF1(bestX1) - m * bestX1; + + string tanEq = $"{m:F4} * x + {c:F4}"; + AddFunctionCurve(tanEq, false, rangeMinX, rangeMaxX, Color.FromArgb(250, 204, 21), DashStyle.Dash, 2.5f); + + // Add contact points + _points.Add(new PlotPoint { X = (float)bestX1, Y = (float)EvalF1(bestX1), Color = Color.FromArgb(56, 189, 248), Shape = PointShape.Diamond }); + _points.Add(new PlotPoint { X = (float)bestX2, Y = (float)EvalF2(bestX2), Color = Color.FromArgb(244, 63, 94), Shape = PointShape.Diamond }); + RefreshPointsList(); + + StringBuilder sb = new StringBuilder(); + sb.AppendLine("✓ ORTAK TEĞET BULUNDU:"); + sb.AppendLine($"Doğru: y = {m:F4}·x + {c:F4}"); + sb.AppendLine($"1. Değme Noktası: P1({bestX1:F3}, {EvalF1(bestX1):F3})"); + sb.AppendLine($"2. Değme Noktası: P2({bestX2:F3}, {EvalF2(bestX2):F3})"); + txtToolLog.Text = sb.ToString(); + } + else + { + txtToolLog.Text = "Belirtilen aralıkta ortak teğet bulunamadı veya eğriler uygun geometriye sahip değil."; + } + } + catch (Exception ex) + { + txtToolLog.Text = "Hata: " + ex.Message; + } + } + + private void BtnNearestPoints_Click(object sender, EventArgs e) + { + string eq1 = cmbToolF1.SelectedItem?.ToString(); + string eq2 = cmbToolF2.SelectedItem?.ToString(); + + if (string.IsNullOrWhiteSpace(eq1) || string.IsNullOrWhiteSpace(eq2)) + { + MessageBox.Show("Lütfen iki fonksiyon seçin.", "Seçim Eksik", MessageBoxButtons.OK, MessageBoxIcon.Information); + return; + } + + try + { + // Check if they intersect: f1 - f2 = 0 + string diffEq = $"({eq1}) - ({eq2})"; + var roots = NumericalMethods.FindAllRoots(diffEq, (decimal)rangeMinX, (decimal)rangeMaxX, "x"); + + if (roots.Count > 0) + { + StringBuilder sbInt = new StringBuilder(); + sbInt.AppendLine("⚠️ FONKSİYONLAR KESİŞİYOR!"); + sbInt.AppendLine($"Kesişme Kökleri ({roots.Count} adet):"); + foreach (var r in roots) + { + sbInt.AppendLine($" • x = {r.Root:F5} (f(x)={r.FVal:G4})"); + } + sbInt.AppendLine("Kesiştikleri için aralarındaki minimum mesafe: 0'dır."); + txtToolLog.Text = sbInt.ToString(); + return; + } + + // If no intersection, find points minimizing Euclidean distance + Function f1 = NumericalMethods.CompileFunction(eq1); + Function f2 = NumericalMethods.CompileFunction(eq2); + + decimal minDistSq = decimal.MaxValue; + decimal bestX1 = 0m, bestX2 = 0m; + decimal bestY1 = 0m, bestY2 = 0m; + + int gridN = 60; + decimal xStart = (decimal)rangeMinX; + decimal xEnd = (decimal)rangeMaxX; + decimal dx = (xEnd - xStart) / gridN; + + for (int i = 0; i <= gridN; i++) + { + decimal x1 = xStart + i * dx; + decimal y1 = 0m; + try { y1 = NumericalMethods.EvaluateCompiled(f1, "x", x1); } catch { continue; } + + for (int j = 0; j <= gridN; j++) + { + decimal x2 = xStart + j * dx; + decimal y2 = 0m; + try { y2 = NumericalMethods.EvaluateCompiled(f2, "x", x2); } catch { continue; } + + decimal dSq = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); + if (dSq < minDistSq) + { + minDistSq = dSq; + bestX1 = x1; + bestY1 = y1; + bestX2 = x2; + bestY2 = y2; + } + } + } + + decimal dist = (decimal)Math.Sqrt((double)minDistSq); + + // Add points + _points.Add(new PlotPoint { X = (float)bestX1, Y = (float)bestY1, Color = Color.FromArgb(236, 72, 153), Shape = PointShape.Diamond }); + _points.Add(new PlotPoint { X = (float)bestX2, Y = (float)bestY2, Color = Color.FromArgb(236, 72, 153), Shape = PointShape.Diamond }); + RefreshPointsList(); + + // Connecting line equation + decimal m = 0m, c = 0m; + string lineEq; + if (DecimalMath.Abs(bestX2 - bestX1) > 1e-5m) + { + m = (bestY2 - bestY1) / (bestX2 - bestX1); + c = bestY1 - m * bestX1; + lineEq = $"{m:F4} * x + {c:F4}"; + AddFunctionCurve(lineEq, false, rangeMinX, rangeMaxX, Color.FromArgb(236, 72, 153), DashStyle.Dot, 2f); + } + else + { + AddVerticalLine((float)bestX1, (float)Math.Min(bestY1, bestY2), (float)Math.Max(bestY1, bestY2), Color.FromArgb(236, 72, 153), DashStyle.Dot); + lineEq = $"x = {bestX1:F4} (Düşey Doğru)"; + } + + StringBuilder sb = new StringBuilder(); + sb.AppendLine("✓ EN YAKIN NOKTALAR HESAPLANDI:"); + sb.AppendLine($"Kesişme: Yok (Denklem kökü bulunamadı)"); + sb.AppendLine($"P1({bestX1:F3}, {bestY1:F3}) ve P2({bestX2:F3}, {bestY2:F3})"); + sb.AppendLine($"Minimum Mesafe: {dist:F5} birim"); + sb.AppendLine($"Geçen Doğru: y = {m:F4}·x + {c:F4}"); + txtToolLog.Text = sb.ToString(); + } + catch (Exception ex) + { + txtToolLog.Text = "Hata: " + ex.Message; + } + } + + private void BtnPointTangent_Click(object sender, EventArgs e) + { + string eq = cmbToolF1.SelectedItem?.ToString(); + if (string.IsNullOrWhiteSpace(eq)) + { + MessageBox.Show("Lütfen 1. Fonksiyonu seçin.", "Fonksiyon Eksik", MessageBoxButtons.OK, MessageBoxIcon.Information); + return; + } + + float px = ParseFloat(txtTanPointX.Text, 0f); + float py = ParseFloat(txtTanPointY.Text, 3f); + + try + { + Function f = NumericalMethods.CompileFunction(eq); + decimal x0 = (decimal)px; + decimal y0 = (decimal)py; + + // Tangent condition: (f(xt) - y0) - f'(xt) * (xt - x0) = 0 + // Search for xt in [rangeMinX, rangeMaxX] + decimal bestDiff = decimal.MaxValue; + decimal bestXt = 0m; + int nScan = 100; + decimal xStart = (decimal)rangeMinX; + decimal xEnd = (decimal)rangeMaxX; + decimal dx = (xEnd - xStart) / nScan; + + for (int i = 0; i <= nScan; i++) + { + decimal xt = xStart + i * dx; + try + { + decimal fx = NumericalMethods.EvaluateCompiled(f, "x", xt); + decimal dfx = EvalDeriv(f, xt); + decimal cond = (fx - y0) - dfx * (xt - x0); + if (DecimalMath.Abs(cond) < bestDiff) + { + bestDiff = DecimalMath.Abs(cond); + bestXt = xt; + } + } + catch { } + } + + if (bestDiff < 0.5m) + { + decimal m = EvalDeriv(f, bestXt); + decimal c = y0 - m * x0; + + string tanEq = $"{m:F4} * x + {c:F4}"; + AddFunctionCurve(tanEq, false, rangeMinX, rangeMaxX, Color.FromArgb(249, 115, 22), DashStyle.Dash, 2.2f); + + // Add point and contact point + _points.Add(new PlotPoint { X = px, Y = py, Color = Color.FromArgb(249, 115, 22), Shape = PointShape.Cross }); + _points.Add(new PlotPoint { X = (float)bestXt, Y = (float)NumericalMethods.EvaluateCompiled(f, "x", bestXt), Color = Color.FromArgb(52, 211, 153), Shape = PointShape.Diamond }); + RefreshPointsList(); + + StringBuilder sb = new StringBuilder(); + sb.AppendLine("✓ NOKTADAN ÇİZİLEN TEĞET DOĞRUSU:"); + sb.AppendLine($"Verilen Nokta: P₀({px}, {py})"); + sb.AppendLine($"Değme Noktası: P_teğet({bestXt:F3}, {NumericalMethods.EvaluateCompiled(f, "x", bestXt):F3})"); + sb.AppendLine($"Teğet Eğim (m): {m:F4}"); + sb.AppendLine($"Teğet Denklemi: y = {m:F4}·x + {c:F4}"); + txtToolLog.Text = sb.ToString(); + } + else + { + txtToolLog.Text = "Verilen noktadan fonksiyona teğet kökü bulunamadı."; + } + } + catch (Exception ex) + { + txtToolLog.Text = "Hata: " + ex.Message; + } + } + + #endregion + + #region Parametric Shapes + + private void BtnAddShape_Click(object sender, EventArgs e) + { + float cx = ParseFloat(txtShapeCenterX.Text, 0f); + float cy = ParseFloat(txtShapeCenterY.Text, 0f); + float d1 = Math.Max(0.1f, ParseFloat(txtShapeDim1.Text, 4f)); + float d2 = Math.Max(0.1f, ParseFloat(txtShapeDim2.Text, 2f)); + + int shapeIdx = cmbShapeType.SelectedIndex; + Color shapeColor = _palette[_colorIndex % _palette.Length]; + _colorIndex++; + + switch (shapeIdx) + { + case 0: // Daire (Çember) + // y = cy ± sqrt(R^2 - (x - cx)^2) + string upCircle = $"{cy:F3} + sqrt({d1 * d1:F4} - (x - {cx:F3})^2)"; + string lowCircle = $"{cy:F3} - sqrt({d1 * d1:F4} - (x - {cx:F3})^2)"; + AddFunctionCurve(upCircle, true, cx - d1, cx + d1, shapeColor, DashStyle.Solid, 2.5f); + AddFunctionCurve(lowCircle, true, cx - d1, cx + d1, shapeColor, DashStyle.Solid, 2.5f); + lblStatus.Text = $"Parametrik Daire eklendi [Merkez: ({cx}, {cy}), Yarıçap: {d1}]"; + break; + + case 1: // Kare (Kenar d1) + float halfSide = d1 / 2f; + // Top, Bottom, Left, Right + AddFunctionCurve($"{cy + halfSide:F3}", true, cx - halfSide, cx + halfSide, shapeColor, DashStyle.Solid, 2.5f); + AddFunctionCurve($"{cy - halfSide:F3}", true, cx - halfSide, cx + halfSide, shapeColor, DashStyle.Solid, 2.5f); + AddVerticalLine(cx - halfSide, cy - halfSide, cy + halfSide, shapeColor, DashStyle.Solid, 2.5f); + AddVerticalLine(cx + halfSide, cy - halfSide, cy + halfSide, shapeColor, DashStyle.Solid, 2.5f); + lblStatus.Text = $"Kare eklendi [Merkez: ({cx}, {cy}), Kenar: {d1}]"; + break; + + case 2: // Dikdörtgen (Genişlik d1, Yükseklik d2) + float hw = d1 / 2f; + float hh = d2 / 2f; + AddFunctionCurve($"{cy + hh:F3}", true, cx - hw, cx + hw, shapeColor, DashStyle.Solid, 2.5f); + AddFunctionCurve($"{cy - hh:F3}", true, cx - hw, cx + hw, shapeColor, DashStyle.Solid, 2.5f); + AddVerticalLine(cx - hw, cy - hh, cy + hh, shapeColor, DashStyle.Solid, 2.5f); + AddVerticalLine(cx + hw, cy - hh, cy + hh, shapeColor, DashStyle.Solid, 2.5f); + lblStatus.Text = $"Dikdörtgen eklendi [Merkez: ({cx}, {cy}), {d1} × {d2}]"; + break; + + case 3: // Eşkenar Üçgen (Yarıçap d1) + // 3 vertices on circle of radius d1 + PointF v1 = new PointF(cx, cy + d1); + PointF v2 = new PointF(cx - d1 * 0.866f, cy - d1 * 0.5f); + PointF v3 = new PointF(cx + d1 * 0.866f, cy - d1 * 0.5f); + + AddLineSegmentCurve(v1, v2, shapeColor); + AddLineSegmentCurve(v2, v3, shapeColor); + AddLineSegmentCurve(v3, v1, shapeColor); + lblStatus.Text = $"Eşkenar Üçgen eklendi [Merkez: ({cx}, {cy})]"; + break; + + case 4: // Elips (a=d1, b=d2) + // y = cy ± (b/a)*sqrt(a^2 - (x - cx)^2) + string upEllipse = $"{cy:F3} + ({d2:F3}/{d1:F3}) * sqrt({d1 * d1:F4} - (x - {cx:F3})^2)"; + string lowEllipse = $"{cy:F3} - ({d2:F3}/{d1:F3}) * sqrt({d1 * d1:F4} - (x - {cx:F3})^2)"; + AddFunctionCurve(upEllipse, true, cx - d1, cx + d1, shapeColor, DashStyle.Solid, 2.5f); + AddFunctionCurve(lowEllipse, true, cx - d1, cx + d1, shapeColor, DashStyle.Solid, 2.5f); + lblStatus.Text = $"Elips eklendi [Merkez: ({cx}, {cy}), a={d1}, b={d2}]"; + break; + + case 5: // Düzgün Altıgen (Yarıçap d1) + PointF[] hex = new PointF[6]; + for (int i = 0; i < 6; i++) + { + double ang = i * Math.PI / 3.0; + hex[i] = new PointF((float)(cx + d1 * Math.Cos(ang)), (float)(cy + d1 * Math.Sin(ang))); + } + for (int i = 0; i < 6; i++) + { + AddLineSegmentCurve(hex[i], hex[(i + 1) % 6], shapeColor); + } + lblStatus.Text = $"Düzgün Altıgen eklendi [Merkez: ({cx}, {cy}), R={d1}]"; + break; + } + } + + private void AddLineSegmentCurve(PointF p1, PointF p2, Color color) + { + if (Math.Abs(p1.X - p2.X) < 1e-4f) + { + AddVerticalLine(p1.X, Math.Min(p1.Y, p2.Y), Math.Max(p1.Y, p2.Y), color, DashStyle.Solid, 2.5f); + return; + } + + float minX = Math.Min(p1.X, p2.X); + float maxX = Math.Max(p1.X, p2.X); + float m = (p2.Y - p1.Y) / (p2.X - p1.X); + float c = p1.Y - m * p1.X; + + string eq = $"{m:F4} * x + {c:F4}"; + AddFunctionCurve(eq, true, minX, maxX, color, DashStyle.Solid, 2.5f); + } + + private static decimal EvalDeriv(Function fn, decimal x) + { + decimal h = 0.0005m; + try + { + decimal fPlus = NumericalMethods.EvaluateCompiled(fn, "x", x + h); + decimal fMinus = NumericalMethods.EvaluateCompiled(fn, "x", x - h); + return (fPlus - fMinus) / (2m * h); + } + catch + { + return 0m; + } + } + + #endregion } } diff --git a/src/ttCalculator/Controls/MultivariableTaylorControl.cs b/src/ttCalculator/Controls/MultivariableTaylorControl.cs index e2c4585..c0dd30a 100644 --- a/src/ttCalculator/Controls/MultivariableTaylorControl.cs +++ b/src/ttCalculator/Controls/MultivariableTaylorControl.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Drawing; using System.Globalization; using System.Linq; +using System.Text; using System.Threading.Tasks; using System.Windows.Forms; @@ -120,13 +121,13 @@ namespace MathApp.Controls return; } - string result = await Task.Run(() => + var (fracPoly, factPoly, decPoly, details) = await Task.Run(() => { bool prevRad = Function.UseRadians; Function.UseRadians = true; try { - return NumericalMethods.MethodMultiVar_TaylorSeries(eq, degree, points); + return NumericalMethods.MethodMultiVar_TaylorSeriesDetailed(eq, degree, points); } finally { @@ -135,13 +136,27 @@ namespace MathApp.Controls }); string varsList = string.Join(", ", points.Keys); - string centerList = string.Join(", ", points.Select(kv => $"{kv.Key}₀={kv.Value}")); + string centerList = string.Join(", ", points.Select(kv => $"{kv.Key}₀ = {kv.Value}")); - txtResult.Text = - $"=== Çok Değişkenli Taylor Açılımı ({degree}. Derece, Çapraz Kısmi Türevler Dahil) ===" + Environment.NewLine + - $"Fonksiyon : f({varsList}) = {eq}" + Environment.NewLine + - $"Merkez : ({centerList})" + Environment.NewLine + Environment.NewLine + - $"T_{degree}({varsList}) ≈ {result}"; + StringBuilder sb = new StringBuilder(); + sb.AppendLine($"=== ÇOK DEĞİŞKENLİ TAYLOR AÇILIMI ({degree}. Derece, Çapraz Kısmi Türevler Dahil) ==="); + sb.AppendLine($"Fonksiyon : f({varsList}) = {eq}"); + sb.AppendLine($"Merkez : ({centerList})"); + sb.AppendLine(); + sb.AppendLine("📐 1) KESİRLİ SADELEŞTİRİLMİŞ FORM:"); + sb.AppendLine($" T_{degree}({varsList}) = {fracPoly}"); + sb.AppendLine(); + sb.AppendLine("📜 2) ANALİTİK FAKTÖRİYELLİ FORM [ (1/α!) · ∂^|α|f / ∂x^α ]:"); + sb.AppendLine($" T_{degree}({varsList}) = {factPoly}"); + sb.AppendLine(); + sb.AppendLine("🔢 3) ONDALIKLI SAYISAL YAKLAŞIM:"); + sb.AppendLine($" T_{degree}({varsList}) = {decPoly}"); + sb.AppendLine(); + sb.AppendLine(new string('=', 65)); + sb.AppendLine("=== KISMİ TÜREVLER, PAYDA VE TERİM KATSAYILARI DETAYI ==="); + sb.AppendLine(string.Join(Environment.NewLine, details)); + + txtResult.Text = sb.ToString(); } catch (Exception ex) { diff --git a/src/ttCalculator/Controls/OdeSolverControl.Designer.cs b/src/ttCalculator/Controls/OdeSolverControl.Designer.cs new file mode 100644 index 0000000..aca0278 --- /dev/null +++ b/src/ttCalculator/Controls/OdeSolverControl.Designer.cs @@ -0,0 +1,262 @@ +using System; +using System.Drawing; +using System.Windows.Forms; + +namespace MathApp.Controls +{ + partial class OdeSolverControl + { + private System.ComponentModel.IContainer components = null; + + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) components.Dispose(); + base.Dispose(disposing); + } + + private void InitializeComponent() + { + this.pnlHeader = ThemeHelper.CreateHeaderPanel( + "Diferansiyel Denklem Çözücü (1 Değişkenli ODE / Başlangıç Değer Problemi)", + "dy/dx = f(x, y) başlangıç değer problemini Euler, Heun (RK2), RK4 ve RK8 (Dormand-Prince) ile çözer."); + + this.pnlControls = new Panel(); + this.pnlPresets = new FlowLayoutPanel(); + this.lblPresets = new Label(); + this.btnEx1 = ThemeHelper.CreateExampleChip("y' = x + y [y(0)=1]"); + this.btnEx2 = ThemeHelper.CreateExampleChip("y' = -2*x*y [y(0)=1]"); + this.btnEx3 = ThemeHelper.CreateExampleChip("y' = cos(x) - y [y(0)=0]"); + this.btnEx4 = ThemeHelper.CreateExampleChip("y' = y*(1 - y/10) [Lojistik]"); + + this.lblEquation = new Label(); + this.txtEquation = new TextBox(); + this.lblMethod = new Label(); + this.cmbMethod = new ComboBox(); + + this.lblX0 = new Label(); + this.txtX0 = new TextBox(); + this.lblY0 = new Label(); + this.txtY0 = new TextBox(); + this.lblXEnd = new Label(); + this.txtXEnd = new TextBox(); + this.lblSteps = new Label(); + this.numSteps = new NumericUpDown(); + + this.btnSolve = ThemeHelper.CreateActionButton("🚀 Denklemi Çöz", 140, 32, true); + this.btnCopy = ThemeHelper.CreateCopyButton("📋 Tabloyu Kopyala"); + + this.pnlCardResult = new Panel(); + this.lblFinalValue = new Label(); + this.lblFinalDetails = new Label(); + + this.txtOutput = new RichTextBox(); + + this.pnlControls.SuspendLayout(); + this.pnlCardResult.SuspendLayout(); + this.SuspendLayout(); + + // pnlControls + this.pnlControls.Dock = DockStyle.Top; + this.pnlControls.Height = 165; + this.pnlControls.BackColor = ThemeHelper.DarkBackground; + this.pnlControls.Padding = new Padding(24, 8, 24, 8); + + // Presets + this.lblPresets.Text = "Hazır Şablonlar:"; + this.lblPresets.AutoSize = true; + this.lblPresets.ForeColor = ThemeHelper.MutedText; + this.lblPresets.Font = new Font("Segoe UI Semibold", 9F, FontStyle.Bold); + this.lblPresets.Margin = new Padding(0, 5, 8, 0); + + this.pnlPresets.Location = new Point(24, 8); + this.pnlPresets.Size = new Size(880, 32); + this.pnlPresets.Controls.Add(this.lblPresets); + this.pnlPresets.Controls.Add(this.btnEx1); + this.pnlPresets.Controls.Add(this.btnEx2); + this.pnlPresets.Controls.Add(this.btnEx3); + this.pnlPresets.Controls.Add(this.btnEx4); + + int yRow1 = 48; + this.lblEquation.Text = "dy/dx = f(x, y):"; + this.lblEquation.Location = new Point(24, yRow1 + 3); + this.lblEquation.AutoSize = true; + this.lblEquation.ForeColor = ThemeHelper.LightText; + this.lblEquation.Font = new Font("Segoe UI Semibold", 10F, FontStyle.Bold); + + this.txtEquation.Location = new Point(135, yRow1); + this.txtEquation.Size = new Size(240, 26); + this.txtEquation.Text = "x + y"; + this.txtEquation.Font = new Font("Consolas", 10.5F); + this.txtEquation.BackColor = ThemeHelper.CardBackground; + this.txtEquation.ForeColor = Color.White; + this.txtEquation.BorderStyle = BorderStyle.FixedSingle; + + this.lblMethod.Text = "Nümerik Yöntem:"; + this.lblMethod.Location = new Point(390, yRow1 + 3); + this.lblMethod.AutoSize = true; + this.lblMethod.ForeColor = ThemeHelper.LightText; + this.lblMethod.Font = new Font("Segoe UI", 9.5F); + + this.cmbMethod.Location = new Point(505, yRow1); + this.cmbMethod.Size = new Size(250, 25); + this.cmbMethod.DropDownStyle = ComboBoxStyle.DropDownList; + this.cmbMethod.BackColor = ThemeHelper.CardBackground; + this.cmbMethod.ForeColor = Color.White; + this.cmbMethod.Font = new Font("Segoe UI", 9.5F); + this.cmbMethod.Items.AddRange(new object[] { + "Runge-Kutta 4 (RK4 - Önerilen)", + "Runge-Kutta 8 (RK8 - Ultra Hassas)", + "Heun / Geliştirilmiş Euler (RK2)", + "Euler Yöntemi (1. Derece Standart)" + }); + this.cmbMethod.SelectedIndex = 0; + + this.btnSolve.Location = new Point(765, yRow1 - 2); + + int yRow2 = 88; + this.lblX0.Text = "x₀ (Başlangıç):"; + this.lblX0.Location = new Point(24, yRow2 + 4); + this.lblX0.AutoSize = true; + this.lblX0.ForeColor = ThemeHelper.LightText; + + this.txtX0.Location = new Point(115, yRow2); + this.txtX0.Size = new Size(55, 25); + this.txtX0.Text = "0"; + this.txtX0.Font = new Font("Consolas", 10F); + this.txtX0.BackColor = ThemeHelper.CardBackground; + this.txtX0.ForeColor = Color.White; + this.txtX0.BorderStyle = BorderStyle.FixedSingle; + + this.lblY0.Text = "y(x₀):"; + this.lblY0.Location = new Point(185, yRow2 + 4); + this.lblY0.AutoSize = true; + this.lblY0.ForeColor = ThemeHelper.LightText; + + this.txtY0.Location = new Point(225, yRow2); + this.txtY0.Size = new Size(55, 25); + this.txtY0.Text = "1"; + this.txtY0.Font = new Font("Consolas", 10F); + this.txtY0.BackColor = ThemeHelper.CardBackground; + this.txtY0.ForeColor = Color.White; + this.txtY0.BorderStyle = BorderStyle.FixedSingle; + + this.lblXEnd.Text = "x_son (Hedef):"; + this.lblXEnd.Location = new Point(295, yRow2 + 4); + this.lblXEnd.AutoSize = true; + this.lblXEnd.ForeColor = ThemeHelper.LightText; + + this.txtXEnd.Location = new Point(385, yRow2); + this.txtXEnd.Size = new Size(60, 25); + this.txtXEnd.Text = "2"; + this.txtXEnd.Font = new Font("Consolas", 10F); + this.txtXEnd.BackColor = ThemeHelper.CardBackground; + this.txtXEnd.ForeColor = Color.White; + this.txtXEnd.BorderStyle = BorderStyle.FixedSingle; + + this.lblSteps.Text = "Adım Sayısı (N):"; + this.lblSteps.Location = new Point(460, yRow2 + 4); + this.lblSteps.AutoSize = true; + this.lblSteps.ForeColor = ThemeHelper.LightText; + + ((System.ComponentModel.ISupportInitialize)(this.numSteps)).BeginInit(); + this.numSteps.Location = new Point(560, yRow2); + this.numSteps.Size = new Size(70, 25); + this.numSteps.Minimum = 2; + this.numSteps.Maximum = 5000; + this.numSteps.Value = 50; + this.numSteps.BackColor = ThemeHelper.CardBackground; + this.numSteps.ForeColor = Color.White; + ((System.ComponentModel.ISupportInitialize)(this.numSteps)).EndInit(); + + this.btnCopy.Location = new Point(650, yRow2 - 1); + + this.pnlControls.Controls.Add(this.pnlPresets); + this.pnlControls.Controls.Add(this.lblEquation); + this.pnlControls.Controls.Add(this.txtEquation); + this.pnlControls.Controls.Add(this.lblMethod); + this.pnlControls.Controls.Add(this.cmbMethod); + this.pnlControls.Controls.Add(this.btnSolve); + this.pnlControls.Controls.Add(this.lblX0); + this.pnlControls.Controls.Add(this.txtX0); + this.pnlControls.Controls.Add(this.lblY0); + this.pnlControls.Controls.Add(this.txtY0); + this.pnlControls.Controls.Add(this.lblXEnd); + this.pnlControls.Controls.Add(this.txtXEnd); + this.pnlControls.Controls.Add(this.lblSteps); + this.pnlControls.Controls.Add(this.numSteps); + this.pnlControls.Controls.Add(this.btnCopy); + + // pnlCardResult (Hero card) + this.pnlCardResult.Dock = DockStyle.Top; + this.pnlCardResult.Height = 70; + this.pnlCardResult.BackColor = ThemeHelper.CardBackground; + this.pnlCardResult.Padding = new Padding(20, 10, 20, 10); + + this.lblFinalValue.Dock = DockStyle.Top; + this.lblFinalValue.Height = 28; + this.lblFinalValue.Font = new Font("Segoe UI Semibold", 14F, FontStyle.Bold); + this.lblFinalValue.ForeColor = Color.FromArgb(52, 211, 153); + this.lblFinalValue.Text = "y(x_son) ≈ —"; + + this.lblFinalDetails.Dock = DockStyle.Bottom; + this.lblFinalDetails.Height = 22; + this.lblFinalDetails.Font = new Font("Segoe UI", 9F); + this.lblFinalDetails.ForeColor = ThemeHelper.MutedText; + this.lblFinalDetails.Text = "Hesaplama bekleniyor."; + + this.pnlCardResult.Controls.Add(this.lblFinalDetails); + this.pnlCardResult.Controls.Add(this.lblFinalValue); + + // txtOutput + this.txtOutput.Dock = DockStyle.Fill; + this.txtOutput.BackColor = Color.FromArgb(11, 17, 32); + this.txtOutput.ForeColor = Color.FromArgb(226, 232, 240); + this.txtOutput.Font = new Font("Consolas", 9.5F); + this.txtOutput.BorderStyle = BorderStyle.None; + this.txtOutput.ReadOnly = true; + + // Assemble OdeSolverControl + this.AutoScaleDimensions = new SizeF(7F, 15F); + this.AutoScaleMode = AutoScaleMode.Font; + this.BackColor = ThemeHelper.DarkBackground; + this.Controls.Add(this.txtOutput); + this.Controls.Add(this.pnlCardResult); + this.Controls.Add(this.pnlControls); + this.Controls.Add(this.pnlHeader); + this.Name = "OdeSolverControl"; + this.Size = new Size(920, 660); + + this.pnlControls.ResumeLayout(false); + this.pnlControls.PerformLayout(); + this.pnlCardResult.ResumeLayout(false); + this.ResumeLayout(false); + } + + private Panel pnlHeader; + private Panel pnlControls; + private FlowLayoutPanel pnlPresets; + private Label lblPresets; + private Button btnEx1; + private Button btnEx2; + private Button btnEx3; + private Button btnEx4; + private Label lblEquation; + private TextBox txtEquation; + private Label lblMethod; + private ComboBox cmbMethod; + private Button btnSolve; + private Label lblX0; + private TextBox txtX0; + private Label lblY0; + private TextBox txtY0; + private Label lblXEnd; + private TextBox txtXEnd; + private Label lblSteps; + private NumericUpDown numSteps; + private Button btnCopy; + private Panel pnlCardResult; + private Label lblFinalValue; + private Label lblFinalDetails; + private RichTextBox txtOutput; + } +} diff --git a/src/ttCalculator/Controls/OdeSolverControl.cs b/src/ttCalculator/Controls/OdeSolverControl.cs new file mode 100644 index 0000000..9b64afb --- /dev/null +++ b/src/ttCalculator/Controls/OdeSolverControl.cs @@ -0,0 +1,146 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Globalization; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace MathApp.Controls +{ + public partial class OdeSolverControl : UserControl + { + public OdeSolverControl() + { + InitializeComponent(); + + btnSolve.Click += BtnSolve_Click; + btnCopy.Click += (s, e) => + { + if (!string.IsNullOrEmpty(txtOutput.Text)) + { + Clipboard.SetText(txtOutput.Text); + MessageBox.Show("Çözüm tablosu panoya kopyalandı!", "Bilgi", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + }; + + btnEx1.Click += (s, e) => LoadPreset("x + y", "0", "1", "2", 50, 0); + btnEx2.Click += (s, e) => LoadPreset("-2*x*y", "0", "1", "2", 50, 0); + btnEx3.Click += (s, e) => LoadPreset("cos(x) - y", "0", "0", "6.28318", 60, 0); + btnEx4.Click += (s, e) => LoadPreset("y*(1 - y/10)", "0", "1", "8", 80, 0); + + txtEquation.KeyDown += Input_KeyDown; + txtX0.KeyDown += Input_KeyDown; + txtY0.KeyDown += Input_KeyDown; + txtXEnd.KeyDown += Input_KeyDown; + } + + private void Input_KeyDown(object sender, KeyEventArgs e) + { + if (e.KeyCode == Keys.Enter) + { + e.SuppressKeyPress = true; + BtnSolve_Click(this, EventArgs.Empty); + } + } + + private void LoadPreset(string eq, string x0, string y0, string xEnd, int steps, int methodIdx) + { + txtEquation.Text = eq; + txtX0.Text = x0; + txtY0.Text = y0; + txtXEnd.Text = xEnd; + numSteps.Value = Math.Max(2, Math.Min(5000, steps)); + cmbMethod.SelectedIndex = methodIdx; + BtnSolve_Click(this, EventArgs.Empty); + } + + private decimal ParseDec(string s, string field) + { + string norm = (s ?? "").Trim().Replace(',', '.'); + if (decimal.TryParse(norm, NumberStyles.Any, CultureInfo.InvariantCulture, out decimal v)) + return v; + throw new ArgumentException($"'{field}' alanı için geçerli bir sayı giriniz."); + } + + private async void BtnSolve_Click(object sender, EventArgs e) + { + string origBtnText = btnSolve.Text; + btnSolve.Enabled = false; + btnSolve.Text = "⏳ Çözülüyor..."; + Cursor = Cursors.WaitCursor; + + try + { + string eq = txtEquation.Text.Trim(); + if (string.IsNullOrWhiteSpace(eq)) + { + txtOutput.Text = "Lütfen dy/dx diferansiyel denklemini giriniz."; + return; + } + + decimal x0 = ParseDec(txtX0.Text, "x₀ (Başlangıç)"); + decimal y0 = ParseDec(txtY0.Text, "y(x₀)"); + decimal xEnd = ParseDec(txtXEnd.Text, "x_son (Hedef)"); + int steps = (int)numSteps.Value; + string method = cmbMethod.SelectedItem?.ToString() ?? "RK4"; + + var results = await Task.Run(() => + { + bool prevRad = Function.UseRadians; + Function.UseRadians = true; + try + { + return DifferentialEquations.SolveOde(eq, x0, y0, xEnd, steps, method); + } + finally + { + Function.UseRadians = prevRad; + } + }); + + if (results != null && results.Count > 0) + { + var last = results[results.Count - 1]; + string lastYStr = last.Y.ToString("0.########", CultureInfo.InvariantCulture); + string lastXStr = last.X.ToString("0.####", CultureInfo.InvariantCulture); + + lblFinalValue.Text = $"y({lastXStr}) ≈ {lastYStr}"; + lblFinalValue.ForeColor = Color.FromArgb(52, 211, 153); + lblFinalDetails.Text = $"✅ {method} ile {steps} adımda h = {((xEnd - x0) / steps).ToString("0.######", CultureInfo.InvariantCulture)} adım boyutuyla başarıyla çözüldü."; + + StringBuilder sb = new StringBuilder(); + sb.AppendLine("=== DİFERANSİYEL DENKLEM NÜMERİK ÇÖZÜM TABLOSU ==="); + sb.AppendLine($" Denklem : dy/dx = {eq}"); + sb.AppendLine($" Başlangıç : y({x0}) = {y0}"); + sb.AppendLine($" Hedef Aralık : [{x0}, {xEnd}] (N = {steps} adım, h = {((xEnd - x0) / steps).ToString("0.######", CultureInfo.InvariantCulture)})"); + sb.AppendLine($" Yöntem : {method}"); + sb.AppendLine(new string('=', 70)); + sb.AppendLine($"{"Adım",-6} | {"x",-16} | {"y (Hesaplanan)",-20} | {"Eğim (dy/dx)",-18}"); + sb.AppendLine(new string('-', 70)); + + for (int i = 0; i < results.Count; i++) + { + var r = results[i]; + sb.AppendLine($"[{i,4}] | {r.X.ToString("0.######", CultureInfo.InvariantCulture),-16} | {r.Y.ToString("0.########", CultureInfo.InvariantCulture),-20} | {r.Slope.ToString("0.######", CultureInfo.InvariantCulture),-18}"); + } + + txtOutput.Text = sb.ToString(); + } + } + catch (Exception ex) + { + txtOutput.Text = "❌ Hata: " + ex.Message; + lblFinalValue.Text = "Hata Oluştu"; + lblFinalValue.ForeColor = Color.FromArgb(239, 68, 68); + lblFinalDetails.Text = ex.Message; + } + finally + { + btnSolve.Enabled = true; + btnSolve.Text = origBtnText; + Cursor = Cursors.Default; + } + } + } +} diff --git a/src/ttCalculator/Controls/OdeSystemSolverControl.Designer.cs b/src/ttCalculator/Controls/OdeSystemSolverControl.Designer.cs new file mode 100644 index 0000000..466b7d3 --- /dev/null +++ b/src/ttCalculator/Controls/OdeSystemSolverControl.Designer.cs @@ -0,0 +1,250 @@ +using System; +using System.Drawing; +using System.Windows.Forms; + +namespace MathApp.Controls +{ + partial class OdeSystemSolverControl + { + private System.ComponentModel.IContainer components = null; + + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) components.Dispose(); + base.Dispose(disposing); + } + + private void InitializeComponent() + { + this.pnlHeader = ThemeHelper.CreateHeaderPanel( + "Diferansiyel Denklem Sistemi Çözücü (System of ODEs / Yüksek Dereceli ODE)", + "dY/dt = F(t, Y) vektörel diferansiyel denklem sistemlerini ve n. derece denklemleri RK4, RK8 ve Euler ile çözer."); + + this.pnlControls = new Panel(); + this.pnlPresets = new FlowLayoutPanel(); + this.lblPresets = new Label(); + this.btnEx1 = ThemeHelper.CreateExampleChip("Harmonik Osilatör [y₁'=y₂, y₂'=-y₁]"); + this.btnEx2 = ThemeHelper.CreateExampleChip("Av-Avcı [Lotka-Volterra]"); + this.btnEx3 = ThemeHelper.CreateExampleChip("Sönümlü Sarkaç [x'=v, v'=-0.3v-sin(x)]"); + this.btnEx4 = ThemeHelper.CreateExampleChip("Lorenz Kaotik Çekicisi [3D]"); + + this.lblEqCount = new Label(); + this.numEqCount = new NumericUpDown(); + this.lblMethod = new Label(); + this.cmbMethod = new ComboBox(); + + this.lblT0 = new Label(); + this.txtT0 = new TextBox(); + this.lblTEnd = new Label(); + this.txtTEnd = new TextBox(); + this.lblSteps = new Label(); + this.numSteps = new NumericUpDown(); + + this.btnSolve = ThemeHelper.CreateActionButton("🚀 Sistemi Çöz", 140, 32, true); + this.btnCopy = ThemeHelper.CreateCopyButton("📋 Tabloyu Kopyala"); + + this.pnlEquations = new Panel(); + + this.pnlCardResult = new Panel(); + this.lblFinalValue = new Label(); + this.lblFinalDetails = new Label(); + + this.txtOutput = new RichTextBox(); + + this.pnlControls.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.numEqCount)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.numSteps)).BeginInit(); + this.pnlCardResult.SuspendLayout(); + this.SuspendLayout(); + + // pnlControls + this.pnlControls.Dock = DockStyle.Top; + this.pnlControls.Height = 110; + this.pnlControls.BackColor = ThemeHelper.DarkBackground; + this.pnlControls.Padding = new Padding(24, 8, 24, 8); + + this.lblPresets.Text = "Hazır Sistemler:"; + this.lblPresets.AutoSize = true; + this.lblPresets.ForeColor = ThemeHelper.MutedText; + this.lblPresets.Font = new Font("Segoe UI Semibold", 9F, FontStyle.Bold); + this.lblPresets.Margin = new Padding(0, 5, 8, 0); + + this.pnlPresets.Location = new Point(24, 8); + this.pnlPresets.Size = new Size(880, 32); + this.pnlPresets.Controls.Add(this.lblPresets); + this.pnlPresets.Controls.Add(this.btnEx1); + this.pnlPresets.Controls.Add(this.btnEx2); + this.pnlPresets.Controls.Add(this.btnEx3); + this.pnlPresets.Controls.Add(this.btnEx4); + + int yRow = 48; + this.lblEqCount.Text = "Denklem Sayısı:"; + this.lblEqCount.Location = new Point(24, yRow + 4); + this.lblEqCount.AutoSize = true; + this.lblEqCount.ForeColor = ThemeHelper.LightText; + + this.numEqCount.Location = new Point(125, yRow); + this.numEqCount.Size = new Size(50, 25); + this.numEqCount.Minimum = 1; + this.numEqCount.Maximum = 6; + this.numEqCount.Value = 2; + this.numEqCount.BackColor = ThemeHelper.CardBackground; + this.numEqCount.ForeColor = Color.White; + + this.lblMethod.Text = "Yöntem:"; + this.lblMethod.Location = new Point(190, yRow + 4); + this.lblMethod.AutoSize = true; + this.lblMethod.ForeColor = ThemeHelper.LightText; + + this.cmbMethod.Location = new Point(250, yRow); + this.cmbMethod.Size = new Size(220, 25); + this.cmbMethod.DropDownStyle = ComboBoxStyle.DropDownList; + this.cmbMethod.BackColor = ThemeHelper.CardBackground; + this.cmbMethod.ForeColor = Color.White; + this.cmbMethod.Font = new Font("Segoe UI", 9.5F); + this.cmbMethod.Items.AddRange(new object[] { + "Runge-Kutta 4 (RK4 - Önerilen)", + "Runge-Kutta 8 (RK8 - Yüksek Hassasiyet)", + "Euler Yöntemi (1. Derece)" + }); + this.cmbMethod.SelectedIndex = 0; + + this.lblT0.Text = "t₀:"; + this.lblT0.Location = new Point(485, yRow + 4); + this.lblT0.AutoSize = true; + this.lblT0.ForeColor = ThemeHelper.LightText; + + this.txtT0.Location = new Point(510, yRow); + this.txtT0.Size = new Size(50, 25); + this.txtT0.Text = "0"; + this.txtT0.Font = new Font("Consolas", 10F); + this.txtT0.BackColor = ThemeHelper.CardBackground; + this.txtT0.ForeColor = Color.White; + this.txtT0.BorderStyle = BorderStyle.FixedSingle; + + this.lblTEnd.Text = "t_son:"; + this.lblTEnd.Location = new Point(570, yRow + 4); + this.lblTEnd.AutoSize = true; + this.lblTEnd.ForeColor = ThemeHelper.LightText; + + this.txtTEnd.Location = new Point(615, yRow); + this.txtTEnd.Size = new Size(50, 25); + this.txtTEnd.Text = "10"; + this.txtTEnd.Font = new Font("Consolas", 10F); + this.txtTEnd.BackColor = ThemeHelper.CardBackground; + this.txtTEnd.ForeColor = Color.White; + this.txtTEnd.BorderStyle = BorderStyle.FixedSingle; + + this.lblSteps.Text = "Adım (N):"; + this.lblSteps.Location = new Point(675, yRow + 4); + this.lblSteps.AutoSize = true; + this.lblSteps.ForeColor = ThemeHelper.LightText; + + this.numSteps.Location = new Point(740, yRow); + this.numSteps.Size = new Size(65, 25); + this.numSteps.Minimum = 2; + this.numSteps.Maximum = 5000; + this.numSteps.Value = 100; + this.numSteps.BackColor = ThemeHelper.CardBackground; + this.numSteps.ForeColor = Color.White; + + this.btnSolve.Location = new Point(24, 78); + this.btnCopy.Location = new Point(175, 78); + + this.pnlControls.Controls.Add(this.pnlPresets); + this.pnlControls.Controls.Add(this.lblEqCount); + this.pnlControls.Controls.Add(this.numEqCount); + this.pnlControls.Controls.Add(this.lblMethod); + this.pnlControls.Controls.Add(this.cmbMethod); + this.pnlControls.Controls.Add(this.lblT0); + this.pnlControls.Controls.Add(this.txtT0); + this.pnlControls.Controls.Add(this.lblTEnd); + this.pnlControls.Controls.Add(this.txtTEnd); + this.pnlControls.Controls.Add(this.lblSteps); + this.pnlControls.Controls.Add(this.numSteps); + this.pnlControls.Controls.Add(this.btnSolve); + this.pnlControls.Controls.Add(this.btnCopy); + + // pnlEquations (Dynamic rows for ODEs) + this.pnlEquations.Dock = DockStyle.Top; + this.pnlEquations.Height = 115; + this.pnlEquations.AutoScroll = true; + this.pnlEquations.BackColor = Color.FromArgb(20, 28, 45); + this.pnlEquations.Padding = new Padding(24, 6, 24, 6); + + // pnlCardResult + this.pnlCardResult.Dock = DockStyle.Top; + this.pnlCardResult.Height = 65; + this.pnlCardResult.BackColor = ThemeHelper.CardBackground; + this.pnlCardResult.Padding = new Padding(20, 8, 20, 8); + + this.lblFinalValue.Dock = DockStyle.Top; + this.lblFinalValue.Height = 26; + this.lblFinalValue.Font = new Font("Segoe UI Semibold", 13F, FontStyle.Bold); + this.lblFinalValue.ForeColor = Color.FromArgb(52, 211, 153); + this.lblFinalValue.Text = "Y(t_son) = —"; + + this.lblFinalDetails.Dock = DockStyle.Bottom; + this.lblFinalDetails.Height = 20; + this.lblFinalDetails.Font = new Font("Segoe UI", 9F); + this.lblFinalDetails.ForeColor = ThemeHelper.MutedText; + this.lblFinalDetails.Text = "Sistem çözümü bekleniyor."; + + this.pnlCardResult.Controls.Add(this.lblFinalDetails); + this.pnlCardResult.Controls.Add(this.lblFinalValue); + + // txtOutput + this.txtOutput.Dock = DockStyle.Fill; + this.txtOutput.BackColor = Color.FromArgb(11, 17, 32); + this.txtOutput.ForeColor = Color.FromArgb(226, 232, 240); + this.txtOutput.Font = new Font("Consolas", 9.5F); + this.txtOutput.BorderStyle = BorderStyle.None; + this.txtOutput.ReadOnly = true; + + // Assemble OdeSystemSolverControl + this.AutoScaleDimensions = new SizeF(7F, 15F); + this.AutoScaleMode = AutoScaleMode.Font; + this.BackColor = ThemeHelper.DarkBackground; + this.Controls.Add(this.txtOutput); + this.Controls.Add(this.pnlCardResult); + this.Controls.Add(this.pnlEquations); + this.Controls.Add(this.pnlControls); + this.Controls.Add(this.pnlHeader); + this.Name = "OdeSystemSolverControl"; + this.Size = new Size(920, 680); + + this.pnlControls.ResumeLayout(false); + this.pnlControls.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)(this.numEqCount)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.numSteps)).EndInit(); + this.pnlCardResult.ResumeLayout(false); + this.ResumeLayout(false); + } + + private Panel pnlHeader; + private Panel pnlControls; + private FlowLayoutPanel pnlPresets; + private Label lblPresets; + private Button btnEx1; + private Button btnEx2; + private Button btnEx3; + private Button btnEx4; + private Label lblEqCount; + private NumericUpDown numEqCount; + private Label lblMethod; + private ComboBox cmbMethod; + private Label lblT0; + private TextBox txtT0; + private Label lblTEnd; + private TextBox txtTEnd; + private Label lblSteps; + private NumericUpDown numSteps; + private Button btnSolve; + private Button btnCopy; + private Panel pnlEquations; + private Panel pnlCardResult; + private Label lblFinalValue; + private Label lblFinalDetails; + private RichTextBox txtOutput; + } +} diff --git a/src/ttCalculator/Controls/OdeSystemSolverControl.cs b/src/ttCalculator/Controls/OdeSystemSolverControl.cs new file mode 100644 index 0000000..a4ebf0a --- /dev/null +++ b/src/ttCalculator/Controls/OdeSystemSolverControl.cs @@ -0,0 +1,321 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Globalization; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace MathApp.Controls +{ + public partial class OdeSystemSolverControl : UserControl + { + private class EqRow + { + public Panel Container; + public Label LblDeriv; + public TextBox TxtEquation; + public Label LblInit; + public TextBox TxtInitVal; + } + + private readonly List _rows = new List(); + + public OdeSystemSolverControl() + { + InitializeComponent(); + SetupEvents(); + BuildRows(2); + SetPresetHarmonic(); + } + + private void SetupEvents() + { + numEqCount.ValueChanged += (s, e) => BuildRows((int)numEqCount.Value); + btnSolve.Click += async (s, e) => await SolveAsync(); + btnCopy.Click += (s, e) => + { + if (!string.IsNullOrWhiteSpace(txtOutput.Text)) + { + Clipboard.SetText(txtOutput.Text); + MessageBox.Show("Sonuç tablosu panoya kopyalandı.", "Kopyalandı", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + }; + + btnEx1.Click += (s, e) => SetPresetHarmonic(); + btnEx2.Click += (s, e) => SetPresetLotkaVolterra(); + btnEx3.Click += (s, e) => SetPresetDampedPendulum(); + btnEx4.Click += (s, e) => SetPresetLorenz(); + } + + private void BuildRows(int count) + { + pnlEquations.SuspendLayout(); + pnlEquations.Controls.Clear(); + _rows.Clear(); + + int yOffset = 4; + for (int i = 1; i <= count; i++) + { + Panel pnlRow = new Panel + { + Location = new Point(10, yOffset), + Size = new Size(860, 32), + BackColor = Color.Transparent + }; + + Label lblD = new Label + { + Text = $"dy{i}/dt =", + Location = new Point(0, 5), + Size = new Size(70, 22), + ForeColor = Color.FromArgb(147, 197, 253), + Font = new Font("Consolas", 10.5F, FontStyle.Bold), + TextAlign = ContentAlignment.MiddleRight + }; + + TextBox txtEq = new TextBox + { + Location = new Point(78, 4), + Size = new Size(380, 24), + Font = new Font("Consolas", 10F), + BackColor = ThemeHelper.CardBackground, + ForeColor = Color.White, + BorderStyle = BorderStyle.FixedSingle, + Text = i == 1 ? "y2" : "-y1" + }; + + Label lblInit = new Label + { + Text = $"y{i}(t₀) =", + Location = new Point(475, 5), + Size = new Size(75, 22), + ForeColor = ThemeHelper.LightText, + Font = new Font("Consolas", 9.5F), + TextAlign = ContentAlignment.MiddleRight + }; + + TextBox txtInit = new TextBox + { + Location = new Point(555, 4), + Size = new Size(90, 24), + Font = new Font("Consolas", 10F), + BackColor = ThemeHelper.CardBackground, + ForeColor = Color.White, + BorderStyle = BorderStyle.FixedSingle, + Text = i == 1 ? "1" : "0" + }; + + pnlRow.Controls.Add(lblD); + pnlRow.Controls.Add(txtEq); + pnlRow.Controls.Add(lblInit); + pnlRow.Controls.Add(txtInit); + + pnlEquations.Controls.Add(pnlRow); + _rows.Add(new EqRow + { + Container = pnlRow, + LblDeriv = lblD, + TxtEquation = txtEq, + LblInit = lblInit, + TxtInitVal = txtInit + }); + + yOffset += 34; + } + + pnlEquations.Height = Math.Max(75, yOffset + 8); + pnlEquations.ResumeLayout(true); + } + + private void SetPresetHarmonic() + { + numEqCount.Value = 2; + txtT0.Text = "0"; + txtTEnd.Text = "6.28318"; + numSteps.Value = 100; + cmbMethod.SelectedIndex = 0; // RK4 + + if (_rows.Count >= 2) + { + _rows[0].TxtEquation.Text = "y2"; + _rows[0].TxtInitVal.Text = "1"; + _rows[1].TxtEquation.Text = "-y1"; + _rows[1].TxtInitVal.Text = "0"; + } + } + + private void SetPresetLotkaVolterra() + { + numEqCount.Value = 2; + txtT0.Text = "0"; + txtTEnd.Text = "15"; + numSteps.Value = 200; + cmbMethod.SelectedIndex = 0; + + if (_rows.Count >= 2) + { + _rows[0].TxtEquation.Text = "0.667 * y1 - 1.333 * y1 * y2"; + _rows[0].TxtInitVal.Text = "1"; + _rows[1].TxtEquation.Text = "-1.0 * y2 + 1.0 * y1 * y2"; + _rows[1].TxtInitVal.Text = "1"; + } + } + + private void SetPresetDampedPendulum() + { + numEqCount.Value = 2; + txtT0.Text = "0"; + txtTEnd.Text = "20"; + numSteps.Value = 200; + cmbMethod.SelectedIndex = 0; + + if (_rows.Count >= 2) + { + _rows[0].TxtEquation.Text = "y2"; + _rows[0].TxtInitVal.Text = "1.57"; + _rows[1].TxtEquation.Text = "-0.25 * y2 - sin(y1)"; + _rows[1].TxtInitVal.Text = "0"; + } + } + + private void SetPresetLorenz() + { + numEqCount.Value = 3; + txtT0.Text = "0"; + txtTEnd.Text = "10"; + numSteps.Value = 500; + cmbMethod.SelectedIndex = 0; + + if (_rows.Count >= 3) + { + _rows[0].TxtEquation.Text = "10 * (y2 - y1)"; + _rows[0].TxtInitVal.Text = "1"; + _rows[1].TxtEquation.Text = "y1 * (28 - y3) - y2"; + _rows[1].TxtInitVal.Text = "1"; + _rows[2].TxtEquation.Text = "y1 * y2 - (8/3) * y3"; + _rows[2].TxtInitVal.Text = "1"; + } + } + + private async Task SolveAsync() + { + try + { + btnSolve.Enabled = false; + btnSolve.Text = "⏳ Hesaplanıyor..."; + + int n = _rows.Count; + List eqList = new List(n); + List varNames = new List(n); + Dictionary inits = new Dictionary(); + + for (int i = 0; i < n; i++) + { + string vName = $"y{i + 1}"; + varNames.Add(vName); + + string eqText = _rows[i].TxtEquation.Text.Trim(); + if (string.IsNullOrWhiteSpace(eqText)) + throw new ArgumentException($"{vName} türev denklemi boş bırakılamaz."); + eqList.Add(eqText); + + if (!decimal.TryParse(_rows[i].TxtInitVal.Text.Replace(',', '.'), NumberStyles.Any, CultureInfo.InvariantCulture, out decimal iv)) + iv = 0m; + inits[vName] = iv; + } + + if (!decimal.TryParse(txtT0.Text.Replace(',', '.'), NumberStyles.Any, CultureInfo.InvariantCulture, out decimal t0)) + t0 = 0m; + if (!decimal.TryParse(txtTEnd.Text.Replace(',', '.'), NumberStyles.Any, CultureInfo.InvariantCulture, out decimal tEnd)) + tEnd = 10m; + + int steps = (int)numSteps.Value; + string method = cmbMethod.SelectedItem?.ToString() ?? "RK4"; + + var results = await Task.Run(() => + { + return DifferentialEquations.SolveOdeSystem( + eqList, + varNames, + inits, + t0, + tEnd, + steps, + method, + "t" + ); + }); + + if (results.Count == 0) + { + lblFinalValue.Text = "Çözüm üretilemedi."; + return; + } + + var last = results.Last(); + StringBuilder sbFinal = new StringBuilder(); + sbFinal.Append($"Y({last.T:F4}) = [ "); + for (int i = 0; i < varNames.Count; i++) + { + string v = varNames[i]; + decimal val = last.YValues.ContainsKey(v) ? last.YValues[v] : 0m; + sbFinal.Append($"{v}={val:F6}"); + if (i < varNames.Count - 1) sbFinal.Append(", "); + } + sbFinal.Append(" ]"); + lblFinalValue.Text = sbFinal.ToString(); + + decimal dt = (tEnd - t0) / steps; + lblFinalDetails.Text = $"Yöntem: {method} | Adım Aralığı (h): {dt:F6} | Toplam Nokta: {results.Count}"; + + // Build Table + StringBuilder sbOut = new StringBuilder(); + sbOut.AppendLine("=========================================================================================="); + sbOut.AppendLine($"DİFERANSİYEL DENKLEM SİSTEMİ NÜMERİK ÇÖZÜM TABLOSU ({method})"); + sbOut.AppendLine($"Aralık: [{t0}, {tEnd}], Adım Sayısı (N): {steps}, Adım Büyüklüğü (h): {dt:F6}"); + sbOut.AppendLine("=========================================================================================="); + + // Header + sbOut.Append(string.Format("{0,-8} | {1,-12}", "Adım", "t")); + foreach (var v in varNames) + { + sbOut.Append(string.Format(" | {0,-14}", v)); + } + sbOut.AppendLine(); + sbOut.AppendLine(new string('-', 24 + varNames.Count * 17)); + + int printInterval = Math.Max(1, results.Count / 100); + for (int i = 0; i < results.Count; i++) + { + if (i % printInterval == 0 || i == results.Count - 1) + { + var row = results[i]; + sbOut.Append(string.Format("{0,-8} | {1,-12:F6}", i, row.T)); + foreach (var v in varNames) + { + decimal val = row.YValues.ContainsKey(v) ? row.YValues[v] : 0m; + sbOut.Append(string.Format(" | {0,-14:F8}", val)); + } + sbOut.AppendLine(); + } + } + + sbOut.AppendLine("=========================================================================================="); + txtOutput.Text = sbOut.ToString(); + } + catch (Exception ex) + { + MessageBox.Show($"Çözüm sırasında hata oluştu:\n{ex.Message}", "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error); + lblFinalValue.Text = "Hata oluştu!"; + lblFinalDetails.Text = ex.Message; + } + finally + { + btnSolve.Enabled = true; + btnSolve.Text = "🚀 Sistemi Çöz"; + } + } + } +} diff --git a/src/ttCalculator/Controls/PdeSolverControl.Designer.cs b/src/ttCalculator/Controls/PdeSolverControl.Designer.cs new file mode 100644 index 0000000..5a7e657 --- /dev/null +++ b/src/ttCalculator/Controls/PdeSolverControl.Designer.cs @@ -0,0 +1,335 @@ +using System; +using System.Drawing; +using System.Windows.Forms; + +namespace MathApp.Controls +{ + partial class PdeSolverControl + { + private System.ComponentModel.IContainer components = null; + + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) components.Dispose(); + base.Dispose(disposing); + } + + private void InitializeComponent() + { + this.pnlHeader = ThemeHelper.CreateHeaderPanel( + "Kısmi Diferansiyel Denklem Çözücü (1D PDE Solver)", + "1 Boyutlu Isı (FTCS), Dalga (Leapfrog) ve Taşınım (Upwind) denklemlerini sonlu farklar yöntemi ile çözer."); + + this.pnlControls = new Panel(); + this.pnlPresets = new FlowLayoutPanel(); + this.lblPresets = new Label(); + this.btnExHeat = ThemeHelper.CreateExampleChip("Isı Yayılımı [sin(πx)]"); + this.btnExWave = ThemeHelper.CreateExampleChip("Titreşen Dalga [c=2, sin(πx)]"); + this.btnExAdvect = ThemeHelper.CreateExampleChip("Taşınım Dalgası [Advection]"); + this.btnExGauss = ThemeHelper.CreateExampleChip("Gauss Sıcaklık Paketi"); + + this.lblPdeType = new Label(); + this.cmbPdeType = new ComboBox(); + + this.lblInitU = new Label(); + this.txtInitU = new TextBox(); + + this.lblInitVel = new Label(); + this.txtInitVel = new TextBox(); + + this.lblParam = new Label(); + this.txtParam = new TextBox(); + + this.lblL = new Label(); + this.txtL = new TextBox(); + + this.lblT = new Label(); + this.txtT = new TextBox(); + + this.lblNx = new Label(); + this.numNx = new NumericUpDown(); + + this.lblNt = new Label(); + this.numNt = new NumericUpDown(); + + this.lblBc = new Label(); + this.txtBcLeft = new TextBox(); + this.txtBcRight = new TextBox(); + + this.btnSolve = ThemeHelper.CreateActionButton("🚀 PDE'yi Çöz", 140, 32, true); + this.btnCopy = ThemeHelper.CreateCopyButton("📋 Tabloyu Kopyala"); + + this.pnlCardResult = new Panel(); + this.lblStability = new Label(); + this.lblDetails = new Label(); + + this.txtOutput = new RichTextBox(); + + this.pnlControls.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.numNx)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.numNt)).BeginInit(); + this.pnlCardResult.SuspendLayout(); + this.SuspendLayout(); + + // pnlControls + this.pnlControls.Dock = DockStyle.Top; + this.pnlControls.Height = 168; + this.pnlControls.BackColor = ThemeHelper.DarkBackground; + this.pnlControls.Padding = new Padding(24, 8, 24, 8); + + this.lblPresets.Text = "Örnek Senaryolar:"; + this.lblPresets.AutoSize = true; + this.lblPresets.ForeColor = ThemeHelper.MutedText; + this.lblPresets.Font = new Font("Segoe UI Semibold", 9F, FontStyle.Bold); + this.lblPresets.Margin = new Padding(0, 5, 8, 0); + + this.pnlPresets.Location = new Point(24, 8); + this.pnlPresets.Size = new Size(880, 32); + this.pnlPresets.Controls.Add(this.lblPresets); + this.pnlPresets.Controls.Add(this.btnExHeat); + this.pnlPresets.Controls.Add(this.btnExWave); + this.pnlPresets.Controls.Add(this.btnExAdvect); + this.pnlPresets.Controls.Add(this.btnExGauss); + + int y1 = 46; + this.lblPdeType.Text = "PDE Türü:"; + this.lblPdeType.Location = new Point(24, y1 + 4); + this.lblPdeType.AutoSize = true; + this.lblPdeType.ForeColor = ThemeHelper.LightText; + + this.cmbPdeType.Location = new Point(90, y1); + this.cmbPdeType.Size = new Size(240, 25); + this.cmbPdeType.DropDownStyle = ComboBoxStyle.DropDownList; + this.cmbPdeType.BackColor = ThemeHelper.CardBackground; + this.cmbPdeType.ForeColor = Color.White; + this.cmbPdeType.Font = new Font("Segoe UI", 9.5F); + this.cmbPdeType.Items.AddRange(new object[] { + "Isı Denklemi [u_t = α·u_xx]", + "Dalga Denklemi [u_tt = c²·u_xx]", + "Taşınım Denklemi [u_t + v·u_x = 0]" + }); + this.cmbPdeType.SelectedIndex = 0; + + this.lblInitU.Text = "u(x, 0) ="; + this.lblInitU.Location = new Point(345, y1 + 4); + this.lblInitU.AutoSize = true; + this.lblInitU.ForeColor = ThemeHelper.LightText; + + this.txtInitU.Location = new Point(410, y1); + this.txtInitU.Size = new Size(220, 25); + this.txtInitU.Text = "sin(pi * x)"; + this.txtInitU.Font = new Font("Consolas", 10F); + this.txtInitU.BackColor = ThemeHelper.CardBackground; + this.txtInitU.ForeColor = Color.White; + this.txtInitU.BorderStyle = BorderStyle.FixedSingle; + + this.lblInitVel.Text = "u_t(x, 0) ="; + this.lblInitVel.Location = new Point(640, y1 + 4); + this.lblInitVel.AutoSize = true; + this.lblInitVel.ForeColor = ThemeHelper.LightText; + + this.txtInitVel.Location = new Point(710, y1); + this.txtInitVel.Size = new Size(160, 25); + this.txtInitVel.Text = "0"; + this.txtInitVel.Font = new Font("Consolas", 10F); + this.txtInitVel.BackColor = ThemeHelper.CardBackground; + this.txtInitVel.ForeColor = Color.White; + this.txtInitVel.BorderStyle = BorderStyle.FixedSingle; + + int y2 = 82; + this.lblParam.Text = "Parametre (α / c / v):"; + this.lblParam.Location = new Point(24, y2 + 4); + this.lblParam.AutoSize = true; + this.lblParam.ForeColor = ThemeHelper.LightText; + + this.txtParam.Location = new Point(155, y2); + this.txtParam.Size = new Size(60, 25); + this.txtParam.Text = "0.1"; + this.txtParam.Font = new Font("Consolas", 10F); + this.txtParam.BackColor = ThemeHelper.CardBackground; + this.txtParam.ForeColor = Color.White; + this.txtParam.BorderStyle = BorderStyle.FixedSingle; + + this.lblL.Text = "Uzunluk L:"; + this.lblL.Location = new Point(225, y2 + 4); + this.lblL.AutoSize = true; + this.lblL.ForeColor = ThemeHelper.LightText; + + this.txtL.Location = new Point(295, y2); + this.txtL.Size = new Size(50, 25); + this.txtL.Text = "1"; + this.txtL.Font = new Font("Consolas", 10F); + this.txtL.BackColor = ThemeHelper.CardBackground; + this.txtL.ForeColor = Color.White; + this.txtL.BorderStyle = BorderStyle.FixedSingle; + + this.lblT.Text = "Süre T:"; + this.lblT.Location = new Point(355, y2 + 4); + this.lblT.AutoSize = true; + this.lblT.ForeColor = ThemeHelper.LightText; + + this.txtT.Location = new Point(405, y2); + this.txtT.Size = new Size(50, 25); + this.txtT.Text = "0.5"; + this.txtT.Font = new Font("Consolas", 10F); + this.txtT.BackColor = ThemeHelper.CardBackground; + this.txtT.ForeColor = Color.White; + this.txtT.BorderStyle = BorderStyle.FixedSingle; + + this.lblNx.Text = "Nx (Mekan):"; + this.lblNx.Location = new Point(465, y2 + 4); + this.lblNx.AutoSize = true; + this.lblNx.ForeColor = ThemeHelper.LightText; + + this.numNx.Location = new Point(545, y2); + this.numNx.Size = new Size(55, 25); + this.numNx.Minimum = 5; + this.numNx.Maximum = 200; + this.numNx.Value = 25; + this.numNx.BackColor = ThemeHelper.CardBackground; + this.numNx.ForeColor = Color.White; + + this.lblNt.Text = "Nt (Zaman):"; + this.lblNt.Location = new Point(610, y2 + 4); + this.lblNt.AutoSize = true; + this.lblNt.ForeColor = ThemeHelper.LightText; + + this.numNt.Location = new Point(690, y2); + this.numNt.Size = new Size(60, 25); + this.numNt.Minimum = 5; + this.numNt.Maximum = 2000; + this.numNt.Value = 150; + this.numNt.BackColor = ThemeHelper.CardBackground; + this.numNt.ForeColor = Color.White; + + this.lblBc.Text = "Sınırlar [u(0), u(L)]:"; + this.lblBc.Location = new Point(760, y2 + 4); + this.lblBc.AutoSize = true; + this.lblBc.ForeColor = ThemeHelper.LightText; + + this.txtBcLeft.Location = new Point(870, y2); + this.txtBcLeft.Size = new Size(35, 25); + this.txtBcLeft.Text = "0"; + this.txtBcLeft.Font = new Font("Consolas", 9F); + this.txtBcLeft.BackColor = ThemeHelper.CardBackground; + this.txtBcLeft.ForeColor = Color.White; + this.txtBcLeft.BorderStyle = BorderStyle.FixedSingle; + + this.txtBcRight.Location = new Point(910, y2); + this.txtBcRight.Size = new Size(35, 25); + this.txtBcRight.Text = "0"; + this.txtBcRight.Font = new Font("Consolas", 9F); + this.txtBcRight.BackColor = ThemeHelper.CardBackground; + this.txtBcRight.ForeColor = Color.White; + this.txtBcRight.BorderStyle = BorderStyle.FixedSingle; + + int y3 = 120; + this.btnSolve.Location = new Point(24, y3); + this.btnCopy.Location = new Point(175, y3); + + this.pnlControls.Controls.Add(this.pnlPresets); + this.pnlControls.Controls.Add(this.lblPdeType); + this.pnlControls.Controls.Add(this.cmbPdeType); + this.pnlControls.Controls.Add(this.lblInitU); + this.pnlControls.Controls.Add(this.txtInitU); + this.pnlControls.Controls.Add(this.lblInitVel); + this.pnlControls.Controls.Add(this.txtInitVel); + this.pnlControls.Controls.Add(this.lblParam); + this.pnlControls.Controls.Add(this.txtParam); + this.pnlControls.Controls.Add(this.lblL); + this.pnlControls.Controls.Add(this.txtL); + this.pnlControls.Controls.Add(this.lblT); + this.pnlControls.Controls.Add(this.txtT); + this.pnlControls.Controls.Add(this.lblNx); + this.pnlControls.Controls.Add(this.numNx); + this.pnlControls.Controls.Add(this.lblNt); + this.pnlControls.Controls.Add(this.numNt); + this.pnlControls.Controls.Add(this.lblBc); + this.pnlControls.Controls.Add(this.txtBcLeft); + this.pnlControls.Controls.Add(this.txtBcRight); + this.pnlControls.Controls.Add(this.btnSolve); + this.pnlControls.Controls.Add(this.btnCopy); + + // pnlCardResult + this.pnlCardResult.Dock = DockStyle.Top; + this.pnlCardResult.Height = 65; + this.pnlCardResult.BackColor = ThemeHelper.CardBackground; + this.pnlCardResult.Padding = new Padding(20, 8, 20, 8); + + this.lblStability.Dock = DockStyle.Top; + this.lblStability.Height = 26; + this.lblStability.Font = new Font("Segoe UI Semibold", 12F, FontStyle.Bold); + this.lblStability.ForeColor = Color.FromArgb(52, 211, 153); + this.lblStability.Text = "Kararlılık & Yöntem: Bekleniyor"; + + this.lblDetails.Dock = DockStyle.Bottom; + this.lblDetails.Height = 20; + this.lblDetails.Font = new Font("Segoe UI", 9F); + this.lblDetails.ForeColor = ThemeHelper.MutedText; + this.lblDetails.Text = "PDE çözümü bekleniyor."; + + this.pnlCardResult.Controls.Add(this.lblDetails); + this.pnlCardResult.Controls.Add(this.lblStability); + + // txtOutput + this.txtOutput.Dock = DockStyle.Fill; + this.txtOutput.BackColor = Color.FromArgb(11, 17, 32); + this.txtOutput.ForeColor = Color.FromArgb(226, 232, 240); + this.txtOutput.Font = new Font("Consolas", 9.5F); + this.txtOutput.BorderStyle = BorderStyle.None; + this.txtOutput.ReadOnly = true; + + // Assemble PdeSolverControl + this.AutoScaleDimensions = new SizeF(7F, 15F); + this.AutoScaleMode = AutoScaleMode.Font; + this.BackColor = ThemeHelper.DarkBackground; + this.Controls.Add(this.txtOutput); + this.Controls.Add(this.pnlCardResult); + this.Controls.Add(this.pnlControls); + this.Controls.Add(this.pnlHeader); + this.Name = "PdeSolverControl"; + this.Size = new Size(960, 680); + + this.pnlControls.ResumeLayout(false); + this.pnlControls.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)(this.numNx)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.numNt)).EndInit(); + this.pnlCardResult.ResumeLayout(false); + this.ResumeLayout(false); + } + + private Panel pnlHeader; + private Panel pnlControls; + private FlowLayoutPanel pnlPresets; + private Label lblPresets; + private Button btnExHeat; + private Button btnExWave; + private Button btnExAdvect; + private Button btnExGauss; + private Label lblPdeType; + private ComboBox cmbPdeType; + private Label lblInitU; + private TextBox txtInitU; + private Label lblInitVel; + private TextBox txtInitVel; + private Label lblParam; + private TextBox txtParam; + private Label lblL; + private TextBox txtL; + private Label lblT; + private TextBox txtT; + private Label lblNx; + private NumericUpDown numNx; + private Label lblNt; + private NumericUpDown numNt; + private Label lblBc; + private TextBox txtBcLeft; + private TextBox txtBcRight; + private Button btnSolve; + private Button btnCopy; + private Panel pnlCardResult; + private Label lblStability; + private Label lblDetails; + private RichTextBox txtOutput; + } +} diff --git a/src/ttCalculator/Controls/PdeSolverControl.cs b/src/ttCalculator/Controls/PdeSolverControl.cs new file mode 100644 index 0000000..36c7e2b --- /dev/null +++ b/src/ttCalculator/Controls/PdeSolverControl.cs @@ -0,0 +1,209 @@ +using System; +using System.Drawing; +using System.Globalization; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace MathApp.Controls +{ + public partial class PdeSolverControl : UserControl + { + public PdeSolverControl() + { + InitializeComponent(); + SetupEvents(); + SetPresetHeat(); + } + + private void SetupEvents() + { + btnSolve.Click += async (s, e) => await SolveAsync(); + btnCopy.Click += (s, e) => + { + if (!string.IsNullOrWhiteSpace(txtOutput.Text)) + { + Clipboard.SetText(txtOutput.Text); + MessageBox.Show("Sonuç tablosu panoya kopyalandı.", "Kopyalandı", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + }; + + btnExHeat.Click += (s, e) => SetPresetHeat(); + btnExWave.Click += (s, e) => SetPresetWave(); + btnExAdvect.Click += (s, e) => SetPresetAdvection(); + btnExGauss.Click += (s, e) => SetPresetGauss(); + + cmbPdeType.SelectedIndexChanged += (s, e) => + { + bool isWave = cmbPdeType.SelectedIndex == 1; + lblInitVel.Visible = isWave; + txtInitVel.Visible = isWave; + if (cmbPdeType.SelectedIndex == 0) lblParam.Text = "Difüzyon Katsayısı (α):"; + else if (cmbPdeType.SelectedIndex == 1) lblParam.Text = "Dalga Hızı (c):"; + else lblParam.Text = "Taşınım Hızı (v):"; + }; + } + + private void SetPresetHeat() + { + cmbPdeType.SelectedIndex = 0; + txtInitU.Text = "sin(pi * x)"; + txtInitVel.Text = "0"; + txtParam.Text = "0.1"; + txtL.Text = "1"; + txtT.Text = "0.5"; + numNx.Value = 25; + numNt.Value = 150; + txtBcLeft.Text = "0"; + txtBcRight.Text = "0"; + } + + private void SetPresetWave() + { + cmbPdeType.SelectedIndex = 1; + txtInitU.Text = "sin(pi * x)"; + txtInitVel.Text = "0"; + txtParam.Text = "2"; + txtL.Text = "1"; + txtT.Text = "1.0"; + numNx.Value = 25; + numNt.Value = 200; + txtBcLeft.Text = "0"; + txtBcRight.Text = "0"; + } + + private void SetPresetAdvection() + { + cmbPdeType.SelectedIndex = 2; + txtInitU.Text = "exp(-40 * (x - 0.3)^2)"; + txtInitVel.Text = "0"; + txtParam.Text = "1"; + txtL.Text = "1"; + txtT.Text = "0.5"; + numNx.Value = 40; + numNt.Value = 150; + txtBcLeft.Text = "0"; + txtBcRight.Text = "0"; + } + + private void SetPresetGauss() + { + cmbPdeType.SelectedIndex = 0; + txtInitU.Text = "exp(-100 * (x - 0.5)^2)"; + txtInitVel.Text = "0"; + txtParam.Text = "0.05"; + txtL.Text = "1"; + txtT.Text = "0.2"; + numNx.Value = 31; + numNt.Value = 200; + txtBcLeft.Text = "0"; + txtBcRight.Text = "0"; + } + + private async Task SolveAsync() + { + try + { + btnSolve.Enabled = false; + btnSolve.Text = "⏳ Hesaplanıyor..."; + + DifferentialEquations.PdeType pdeType; + if (cmbPdeType.SelectedIndex == 0) pdeType = DifferentialEquations.PdeType.HeatEquation; + else if (cmbPdeType.SelectedIndex == 1) pdeType = DifferentialEquations.PdeType.WaveEquation; + else pdeType = DifferentialEquations.PdeType.AdvectionEquation; + + string initU = txtInitU.Text.Trim(); + string initVel = txtInitVel.Text.Trim(); + + if (!decimal.TryParse(txtParam.Text.Replace(',', '.'), NumberStyles.Any, CultureInfo.InvariantCulture, out decimal paramVal)) + paramVal = 0.1m; + if (!decimal.TryParse(txtL.Text.Replace(',', '.'), NumberStyles.Any, CultureInfo.InvariantCulture, out decimal lengthL)) + lengthL = 1m; + if (!decimal.TryParse(txtT.Text.Replace(',', '.'), NumberStyles.Any, CultureInfo.InvariantCulture, out decimal totalTimeT)) + totalTimeT = 0.5m; + + int nx = (int)numNx.Value; + int nt = (int)numNt.Value; + + if (!decimal.TryParse(txtBcLeft.Text.Replace(',', '.'), NumberStyles.Any, CultureInfo.InvariantCulture, out decimal bcLeft)) + bcLeft = 0m; + if (!decimal.TryParse(txtBcRight.Text.Replace(',', '.'), NumberStyles.Any, CultureInfo.InvariantCulture, out decimal bcRight)) + bcRight = 0m; + + var grid = await Task.Run(() => + { + return DifferentialEquations.Solve1DPde( + pdeType, + initU, + lengthL, + totalTimeT, + nx, + nt, + paramVal, + bcLeft, + bcRight, + initVel + ); + }); + + lblStability.Text = grid.StabilityNote; + decimal dx = lengthL / (nx - 1); + decimal dt = totalTimeT / (nt - 1); + lblDetails.Text = $"Izgara: {nx} mekan × {nt} zaman noktası | Δx = {dx:F4}, Δt = {dt:F6} | x ∈ [0, {lengthL}], t ∈ [0, {totalTimeT}]"; + + // Format Table of Time Slices + StringBuilder sb = new StringBuilder(); + sb.AppendLine("=========================================================================================="); + sb.AppendLine($"1 BOYUTLU KISMİ DİFERANSİYEL DENKLEM (PDE) ÇÖZÜM TABLOSU"); + sb.AppendLine(grid.StabilityNote); + sb.AppendLine($"Izgara: {nx} mekan noktası, {nt} zaman adımı | dx = {dx:F5}, dt = {dt:F5}"); + sb.AppendLine("=========================================================================================="); + + // Select 5 key time slices: t=0, 25%, 50%, 75%, 100% + int[] timeIndices = new int[] + { + 0, + nt / 4, + nt / 2, + (3 * nt) / 4, + nt - 1 + }; + + sb.Append(string.Format("{0,-8} | {1,-10}", "Nokta i", "x")); + foreach (int tIdx in timeIndices) + { + decimal tVal = grid.TGrid[tIdx]; + sb.Append(string.Format(" | {0,-14}", $"u(x, t={tVal:F3})")); + } + sb.AppendLine(); + sb.AppendLine(new string('-', 22 + timeIndices.Length * 17)); + + for (int i = 0; i < nx; i++) + { + decimal xVal = grid.XGrid[i]; + sb.Append(string.Format("{0,-8} | {1,-10:F4}", i, xVal)); + foreach (int tIdx in timeIndices) + { + decimal uVal = grid.U[i, tIdx]; + sb.Append(string.Format(" | {0,-14:F6}", uVal)); + } + sb.AppendLine(); + } + + sb.AppendLine("=========================================================================================="); + txtOutput.Text = sb.ToString(); + } + catch (Exception ex) + { + MessageBox.Show($"PDE çözümü sırasında hata oluştu:\n{ex.Message}", "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error); + lblStability.Text = "Hata oluştu!"; + lblDetails.Text = ex.Message; + } + finally + { + btnSolve.Enabled = true; + btnSolve.Text = "🚀 PDE'yi Çöz"; + } + } + } +} diff --git a/src/ttCalculator/Controls/PdeSystemSolverControl.Designer.cs b/src/ttCalculator/Controls/PdeSystemSolverControl.Designer.cs new file mode 100644 index 0000000..427c357 --- /dev/null +++ b/src/ttCalculator/Controls/PdeSystemSolverControl.Designer.cs @@ -0,0 +1,339 @@ +using System; +using System.Drawing; +using System.Windows.Forms; + +namespace MathApp.Controls +{ + partial class PdeSystemSolverControl + { + private System.ComponentModel.IContainer components = null; + + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) components.Dispose(); + base.Dispose(disposing); + } + + private void InitializeComponent() + { + this.pnlHeader = ThemeHelper.CreateHeaderPanel( + "Kısmi Diferansiyel Denklem Sistemi Çözücü (Coupled PDE System)", + "Bağlaşımlı Reaksiyon-Difüzyon Kısmi Diferansiyel Denklem Sistemlerini (u_t = Du·u_xx + F(u,v), v_t = Dv·v_xx + G(u,v)) çözer."); + + this.pnlControls = new Panel(); + this.pnlPresets = new FlowLayoutPanel(); + this.lblPresets = new Label(); + this.btnExGrayScott = ThemeHelper.CreateExampleChip("Gray-Scott Deseni"); + this.btnExSchnakenberg = ThemeHelper.CreateExampleChip("Schnakenberg Modeli"); + this.btnExFitzHugh = ThemeHelper.CreateExampleChip("FitzHugh-Nagumo"); + this.btnExDiffusion = ThemeHelper.CreateExampleChip("Çift Difüzyon"); + + this.lblReactionF = new Label(); + this.txtReactionF = new TextBox(); + + this.lblReactionG = new Label(); + this.txtReactionG = new TextBox(); + + this.lblInitU = new Label(); + this.txtInitU = new TextBox(); + + this.lblInitV = new Label(); + this.txtInitV = new TextBox(); + + this.lblDu = new Label(); + this.txtDu = new TextBox(); + + this.lblDv = new Label(); + this.txtDv = new TextBox(); + + this.lblL = new Label(); + this.txtL = new TextBox(); + + this.lblT = new Label(); + this.txtT = new TextBox(); + + this.lblNx = new Label(); + this.numNx = new NumericUpDown(); + + this.lblNt = new Label(); + this.numNt = new NumericUpDown(); + + this.btnSolve = ThemeHelper.CreateActionButton("🚀 PDE Sistemini Çöz", 160, 32, true); + this.btnCopy = ThemeHelper.CreateCopyButton("📋 Tabloyu Kopyala"); + + this.pnlCardResult = new Panel(); + this.lblSummary = new Label(); + this.lblDetails = new Label(); + + this.txtOutput = new RichTextBox(); + + this.pnlControls.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.numNx)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.numNt)).BeginInit(); + this.pnlCardResult.SuspendLayout(); + this.SuspendLayout(); + + // pnlControls + this.pnlControls.Dock = DockStyle.Top; + this.pnlControls.Height = 175; + this.pnlControls.BackColor = ThemeHelper.DarkBackground; + this.pnlControls.Padding = new Padding(24, 8, 24, 8); + + this.lblPresets.Text = "Hazır Modeller:"; + this.lblPresets.AutoSize = true; + this.lblPresets.ForeColor = ThemeHelper.MutedText; + this.lblPresets.Font = new Font("Segoe UI Semibold", 9F, FontStyle.Bold); + this.lblPresets.Margin = new Padding(0, 5, 8, 0); + + this.pnlPresets.Location = new Point(24, 8); + this.pnlPresets.Size = new Size(880, 32); + this.pnlPresets.Controls.Add(this.lblPresets); + this.pnlPresets.Controls.Add(this.btnExGrayScott); + this.pnlPresets.Controls.Add(this.btnExSchnakenberg); + this.pnlPresets.Controls.Add(this.btnExFitzHugh); + this.pnlPresets.Controls.Add(this.btnExDiffusion); + + int y1 = 44; + this.lblReactionF.Text = "F(u, v) [u reaksiyonu]:"; + this.lblReactionF.Location = new Point(24, y1 + 4); + this.lblReactionF.AutoSize = true; + this.lblReactionF.ForeColor = Color.FromArgb(147, 197, 253); + + this.txtReactionF.Location = new Point(160, y1); + this.txtReactionF.Size = new Size(270, 25); + this.txtReactionF.Text = "-u * v^2 + 0.04 * (1 - u)"; + this.txtReactionF.Font = new Font("Consolas", 10F); + this.txtReactionF.BackColor = ThemeHelper.CardBackground; + this.txtReactionF.ForeColor = Color.White; + this.txtReactionF.BorderStyle = BorderStyle.FixedSingle; + + this.lblReactionG.Text = "G(u, v) [v reaksiyonu]:"; + this.lblReactionG.Location = new Point(450, y1 + 4); + this.lblReactionG.AutoSize = true; + this.lblReactionG.ForeColor = Color.FromArgb(249, 168, 212); + + this.txtReactionG.Location = new Point(590, y1); + this.txtReactionG.Size = new Size(270, 25); + this.txtReactionG.Text = "u * v^2 - 0.09 * v"; + this.txtReactionG.Font = new Font("Consolas", 10F); + this.txtReactionG.BackColor = ThemeHelper.CardBackground; + this.txtReactionG.ForeColor = Color.White; + this.txtReactionG.BorderStyle = BorderStyle.FixedSingle; + + int y2 = 78; + this.lblInitU.Text = "u(x, 0) ="; + this.lblInitU.Location = new Point(24, y2 + 4); + this.lblInitU.AutoSize = true; + this.lblInitU.ForeColor = ThemeHelper.LightText; + + this.txtInitU.Location = new Point(80, y2); + this.txtInitU.Size = new Size(160, 25); + this.txtInitU.Text = "1 - 0.5 * exp(-100*(x-0.5)^2)"; + this.txtInitU.Font = new Font("Consolas", 9.5F); + this.txtInitU.BackColor = ThemeHelper.CardBackground; + this.txtInitU.ForeColor = Color.White; + this.txtInitU.BorderStyle = BorderStyle.FixedSingle; + + this.lblInitV.Text = "v(x, 0) ="; + this.lblInitV.Location = new Point(255, y2 + 4); + this.lblInitV.AutoSize = true; + this.lblInitV.ForeColor = ThemeHelper.LightText; + + this.txtInitV.Location = new Point(310, y2); + this.txtInitV.Size = new Size(160, 25); + this.txtInitV.Text = "0.25 * exp(-100*(x-0.5)^2)"; + this.txtInitV.Font = new Font("Consolas", 9.5F); + this.txtInitV.BackColor = ThemeHelper.CardBackground; + this.txtInitV.ForeColor = Color.White; + this.txtInitV.BorderStyle = BorderStyle.FixedSingle; + + this.lblDu.Text = "Du:"; + this.lblDu.Location = new Point(485, y2 + 4); + this.lblDu.AutoSize = true; + this.lblDu.ForeColor = ThemeHelper.LightText; + + this.txtDu.Location = new Point(515, y2); + this.txtDu.Size = new Size(55, 25); + this.txtDu.Text = "0.001"; + this.txtDu.Font = new Font("Consolas", 9.5F); + this.txtDu.BackColor = ThemeHelper.CardBackground; + this.txtDu.ForeColor = Color.White; + this.txtDu.BorderStyle = BorderStyle.FixedSingle; + + this.lblDv.Text = "Dv:"; + this.lblDv.Location = new Point(585, y2 + 4); + this.lblDv.AutoSize = true; + this.lblDv.ForeColor = ThemeHelper.LightText; + + this.txtDv.Location = new Point(615, y2); + this.txtDv.Size = new Size(55, 25); + this.txtDv.Text = "0.0005"; + this.txtDv.Font = new Font("Consolas", 9.5F); + this.txtDv.BackColor = ThemeHelper.CardBackground; + this.txtDv.ForeColor = Color.White; + this.txtDv.BorderStyle = BorderStyle.FixedSingle; + + this.lblL.Text = "L:"; + this.lblL.Location = new Point(685, y2 + 4); + this.lblL.AutoSize = true; + this.lblL.ForeColor = ThemeHelper.LightText; + + this.txtL.Location = new Point(705, y2); + this.txtL.Size = new Size(40, 25); + this.txtL.Text = "1"; + this.txtL.Font = new Font("Consolas", 9.5F); + this.txtL.BackColor = ThemeHelper.CardBackground; + this.txtL.ForeColor = Color.White; + this.txtL.BorderStyle = BorderStyle.FixedSingle; + + this.lblT.Text = "T:"; + this.lblT.Location = new Point(755, y2 + 4); + this.lblT.AutoSize = true; + this.lblT.ForeColor = ThemeHelper.LightText; + + this.txtT.Location = new Point(775, y2); + this.txtT.Size = new Size(40, 25); + this.txtT.Text = "1.0"; + this.txtT.Font = new Font("Consolas", 9.5F); + this.txtT.BackColor = ThemeHelper.CardBackground; + this.txtT.ForeColor = Color.White; + this.txtT.BorderStyle = BorderStyle.FixedSingle; + + this.lblNx.Text = "Nx:"; + this.lblNx.Location = new Point(825, y2 + 4); + this.lblNx.AutoSize = true; + this.lblNx.ForeColor = ThemeHelper.LightText; + + this.numNx.Location = new Point(855, y2); + this.numNx.Size = new Size(45, 25); + this.numNx.Minimum = 5; + this.numNx.Maximum = 200; + this.numNx.Value = 25; + this.numNx.BackColor = ThemeHelper.CardBackground; + this.numNx.ForeColor = Color.White; + + int y3 = 120; + this.lblNt.Text = "Zaman Adımı (Nt):"; + this.lblNt.Location = new Point(24, y3 + 6); + this.lblNt.AutoSize = true; + this.lblNt.ForeColor = ThemeHelper.LightText; + + this.numNt.Location = new Point(135, y3 + 2); + this.numNt.Size = new Size(60, 25); + this.numNt.Minimum = 10; + this.numNt.Maximum = 2000; + this.numNt.Value = 150; + this.numNt.BackColor = ThemeHelper.CardBackground; + this.numNt.ForeColor = Color.White; + + this.btnSolve.Location = new Point(220, y3); + this.btnCopy.Location = new Point(390, y3); + + this.pnlControls.Controls.Add(this.pnlPresets); + this.pnlControls.Controls.Add(this.lblReactionF); + this.pnlControls.Controls.Add(this.txtReactionF); + this.pnlControls.Controls.Add(this.lblReactionG); + this.pnlControls.Controls.Add(this.txtReactionG); + this.pnlControls.Controls.Add(this.lblInitU); + this.pnlControls.Controls.Add(this.txtInitU); + this.pnlControls.Controls.Add(this.lblInitV); + this.pnlControls.Controls.Add(this.txtInitV); + this.pnlControls.Controls.Add(this.lblDu); + this.pnlControls.Controls.Add(this.txtDu); + this.pnlControls.Controls.Add(this.lblDv); + this.pnlControls.Controls.Add(this.txtDv); + this.pnlControls.Controls.Add(this.lblL); + this.pnlControls.Controls.Add(this.txtL); + this.pnlControls.Controls.Add(this.lblT); + this.pnlControls.Controls.Add(this.txtT); + this.pnlControls.Controls.Add(this.lblNx); + this.pnlControls.Controls.Add(this.numNx); + this.pnlControls.Controls.Add(this.lblNt); + this.pnlControls.Controls.Add(this.numNt); + this.pnlControls.Controls.Add(this.btnSolve); + this.pnlControls.Controls.Add(this.btnCopy); + + // pnlCardResult + this.pnlCardResult.Dock = DockStyle.Top; + this.pnlCardResult.Height = 65; + this.pnlCardResult.BackColor = ThemeHelper.CardBackground; + this.pnlCardResult.Padding = new Padding(20, 8, 20, 8); + + this.lblSummary.Dock = DockStyle.Top; + this.lblSummary.Height = 26; + this.lblSummary.Font = new Font("Segoe UI Semibold", 12F, FontStyle.Bold); + this.lblSummary.ForeColor = Color.FromArgb(52, 211, 153); + this.lblSummary.Text = "PDE Sistemi: Çözüm Bekleniyor"; + + this.lblDetails.Dock = DockStyle.Bottom; + this.lblDetails.Height = 20; + this.lblDetails.Font = new Font("Segoe UI", 9F); + this.lblDetails.ForeColor = ThemeHelper.MutedText; + this.lblDetails.Text = "Hazır modelleri seçebilir veya kendi reaksiyon denklemlerinizi yazabilirsiniz."; + + this.pnlCardResult.Controls.Add(this.lblDetails); + this.pnlCardResult.Controls.Add(this.lblSummary); + + // txtOutput + this.txtOutput.Dock = DockStyle.Fill; + this.txtOutput.BackColor = Color.FromArgb(11, 17, 32); + this.txtOutput.ForeColor = Color.FromArgb(226, 232, 240); + this.txtOutput.Font = new Font("Consolas", 9.5F); + this.txtOutput.BorderStyle = BorderStyle.None; + this.txtOutput.ReadOnly = true; + + // Assemble PdeSystemSolverControl + this.AutoScaleDimensions = new SizeF(7F, 15F); + this.AutoScaleMode = AutoScaleMode.Font; + this.BackColor = ThemeHelper.DarkBackground; + this.Controls.Add(this.txtOutput); + this.Controls.Add(this.pnlCardResult); + this.Controls.Add(this.pnlControls); + this.Controls.Add(this.pnlHeader); + this.Name = "PdeSystemSolverControl"; + this.Size = new Size(960, 680); + + this.pnlControls.ResumeLayout(false); + this.pnlControls.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)(this.numNx)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.numNt)).EndInit(); + this.pnlCardResult.ResumeLayout(false); + this.ResumeLayout(false); + } + + private Panel pnlHeader; + private Panel pnlControls; + private FlowLayoutPanel pnlPresets; + private Label lblPresets; + private Button btnExGrayScott; + private Button btnExSchnakenberg; + private Button btnExFitzHugh; + private Button btnExDiffusion; + private Label lblReactionF; + private TextBox txtReactionF; + private Label lblReactionG; + private TextBox txtReactionG; + private Label lblInitU; + private TextBox txtInitU; + private Label lblInitV; + private TextBox txtInitV; + private Label lblDu; + private TextBox txtDu; + private Label lblDv; + private TextBox txtDv; + private Label lblL; + private TextBox txtL; + private Label lblT; + private TextBox txtT; + private Label lblNx; + private NumericUpDown numNx; + private Label lblNt; + private NumericUpDown numNt; + private Button btnSolve; + private Button btnCopy; + private Panel pnlCardResult; + private Label lblSummary; + private Label lblDetails; + private RichTextBox txtOutput; + } +} diff --git a/src/ttCalculator/Controls/PdeSystemSolverControl.cs b/src/ttCalculator/Controls/PdeSystemSolverControl.cs new file mode 100644 index 0000000..50948c1 --- /dev/null +++ b/src/ttCalculator/Controls/PdeSystemSolverControl.cs @@ -0,0 +1,188 @@ +using System; +using System.Drawing; +using System.Globalization; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace MathApp.Controls +{ + public partial class PdeSystemSolverControl : UserControl + { + public PdeSystemSolverControl() + { + InitializeComponent(); + SetupEvents(); + SetPresetGrayScott(); + } + + private void SetupEvents() + { + btnSolve.Click += async (s, e) => await SolveAsync(); + btnCopy.Click += (s, e) => + { + if (!string.IsNullOrWhiteSpace(txtOutput.Text)) + { + Clipboard.SetText(txtOutput.Text); + MessageBox.Show("Sonuç tablosu panoya kopyalandı.", "Kopyalandı", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + }; + + btnExGrayScott.Click += (s, e) => SetPresetGrayScott(); + btnExSchnakenberg.Click += (s, e) => SetPresetSchnakenberg(); + btnExFitzHugh.Click += (s, e) => SetPresetFitzHugh(); + btnExDiffusion.Click += (s, e) => SetPresetDiffusion(); + } + + private void SetPresetGrayScott() + { + txtReactionF.Text = "-u * v^2 + 0.04 * (1 - u)"; + txtReactionG.Text = "u * v^2 - 0.09 * v"; + txtInitU.Text = "1 - 0.5 * exp(-100 * (x - 0.5)^2)"; + txtInitV.Text = "0.25 * exp(-100 * (x - 0.5)^2)"; + txtDu.Text = "0.001"; + txtDv.Text = "0.0005"; + txtL.Text = "1"; + txtT.Text = "1.0"; + numNx.Value = 25; + numNt.Value = 150; + } + + private void SetPresetSchnakenberg() + { + txtReactionF.Text = "0.1 - u + u^2 * v"; + txtReactionG.Text = "0.9 - u^2 * v"; + txtInitU.Text = "1 + 0.1 * cos(2 * pi * x)"; + txtInitV.Text = "0.9 + 0.1 * cos(2 * pi * x)"; + txtDu.Text = "0.001"; + txtDv.Text = "0.01"; + txtL.Text = "1"; + txtT.Text = "1.0"; + numNx.Value = 25; + numNt.Value = 150; + } + + private void SetPresetFitzHugh() + { + txtReactionF.Text = "u - (u^3) / 3 - v"; + txtReactionG.Text = "0.08 * (u + 0.7 - 0.8 * v)"; + txtInitU.Text = "exp(-50 * (x - 0.5)^2)"; + txtInitV.Text = "0"; + txtDu.Text = "0.005"; + txtDv.Text = "0.0001"; + txtL.Text = "1"; + txtT.Text = "2.0"; + numNx.Value = 25; + numNt.Value = 200; + } + + private void SetPresetDiffusion() + { + txtReactionF.Text = "0"; + txtReactionG.Text = "0"; + txtInitU.Text = "sin(pi * x)"; + txtInitV.Text = "cos(pi * x)"; + txtDu.Text = "0.05"; + txtDv.Text = "0.01"; + txtL.Text = "1"; + txtT.Text = "0.5"; + numNx.Value = 25; + numNt.Value = 150; + } + + private async Task SolveAsync() + { + try + { + btnSolve.Enabled = false; + btnSolve.Text = "⏳ Hesaplanıyor..."; + + string fU = txtReactionF.Text.Trim(); + string gV = txtReactionG.Text.Trim(); + string initU = txtInitU.Text.Trim(); + string initV = txtInitV.Text.Trim(); + + if (!decimal.TryParse(txtDu.Text.Replace(',', '.'), NumberStyles.Any, CultureInfo.InvariantCulture, out decimal du)) + du = 0.001m; + if (!decimal.TryParse(txtDv.Text.Replace(',', '.'), NumberStyles.Any, CultureInfo.InvariantCulture, out decimal dv)) + dv = 0.0005m; + if (!decimal.TryParse(txtL.Text.Replace(',', '.'), NumberStyles.Any, CultureInfo.InvariantCulture, out decimal lengthL)) + lengthL = 1m; + if (!decimal.TryParse(txtT.Text.Replace(',', '.'), NumberStyles.Any, CultureInfo.InvariantCulture, out decimal totalTimeT)) + totalTimeT = 1.0m; + + int nx = (int)numNx.Value; + int nt = (int)numNt.Value; + + var grid = await Task.Run(() => + { + return DifferentialEquations.SolveCoupledPdeSystem( + fU, + gV, + initU, + initV, + lengthL, + totalTimeT, + nx, + nt, + du, + dv + ); + }); + + lblSummary.Text = grid.SystemInfo; + decimal dx = lengthL / (nx - 1); + decimal dt = totalTimeT / (nt - 1); + lblDetails.Text = $"Izgara: {nx} mekan × {nt} zaman | Boyut: x ∈ [0, {lengthL}], t ∈ [0, {totalTimeT}] | Sıfır-Akı (Neumann) Sınırları"; + + // Format Table + StringBuilder sb = new StringBuilder(); + sb.AppendLine("=========================================================================================="); + sb.AppendLine("BAĞLAŞIMLI KISMİ DİFERANSİYEL DENKLEM SİSTEMİ (1B REAKSİYON-DİFÜZYON) ÇÖZÜMÜ"); + sb.AppendLine($"F(u,v) = {fU} | G(u,v) = {gV}"); + sb.AppendLine($"Du = {du:G4}, Dv = {dv:G4}, L = {lengthL}, T = {totalTimeT}, dx = {dx:F5}, dt = {dt:F5}"); + sb.AppendLine("=========================================================================================="); + + // Time slices: t = 0, t = T/2, t = T + int t0Idx = 0; + int tMidIdx = nt / 2; + int tEndIdx = nt - 1; + + decimal t0Val = grid.TGrid[t0Idx]; + decimal tMidVal = grid.TGrid[tMidIdx]; + decimal tEndVal = grid.TGrid[tEndIdx]; + + sb.Append(string.Format("{0,-6} | {1,-8}", "Nokta", "x")); + sb.Append(string.Format(" | {0,-12} | {1,-12}", $"u(t={t0Val:F2})", $"v(t={t0Val:F2})")); + sb.Append(string.Format(" | {0,-12} | {1,-12}", $"u(t={tMidVal:F2})", $"v(t={tMidVal:F2})")); + sb.Append(string.Format(" | {0,-12} | {1,-12}", $"u(t={tEndVal:F2})", $"v(t={tEndVal:F2})")); + sb.AppendLine(); + sb.AppendLine(new string('-', 92)); + + for (int i = 0; i < nx; i++) + { + decimal xVal = grid.XGrid[i]; + sb.Append(string.Format("{0,-6} | {1,-8:F3}", i, xVal)); + sb.Append(string.Format(" | {0,-12:F5} | {1,-12:F5}", grid.U[i, t0Idx], grid.V[i, t0Idx])); + sb.Append(string.Format(" | {0,-12:F5} | {1,-12:F5}", grid.U[i, tMidIdx], grid.V[i, tMidIdx])); + sb.Append(string.Format(" | {0,-12:F5} | {1,-12:F5}", grid.U[i, tEndIdx], grid.V[i, tEndIdx])); + sb.AppendLine(); + } + + sb.AppendLine("=========================================================================================="); + txtOutput.Text = sb.ToString(); + } + catch (Exception ex) + { + MessageBox.Show($"PDE Sistemi çözümü sırasında hata oluştu:\n{ex.Message}", "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error); + lblSummary.Text = "Hata oluştu!"; + lblDetails.Text = ex.Message; + } + finally + { + btnSolve.Enabled = true; + btnSolve.Text = "🚀 PDE Sistemini Çöz"; + } + } + } +} diff --git a/src/ttCalculator/Controls/RootFinderControl.Designer.cs b/src/ttCalculator/Controls/RootFinderControl.Designer.cs index 36f1a7c..7a02012 100644 --- a/src/ttCalculator/Controls/RootFinderControl.Designer.cs +++ b/src/ttCalculator/Controls/RootFinderControl.Designer.cs @@ -117,7 +117,8 @@ namespace MathApp.Controls "Newton-Raphson (Türev Tabanlı — En Hızlı Yakınsama)", "Bisection (İkiye Bölme — Garantili Aralık Yakınsaması)", "Secant (Kiriş Yöntemi — Türev Gerektirmeyen Yaklaşım)", - "Regula Falsi (Doğrusal İnterpolasyon ile Kök Bulma)" + "Regula Falsi (Doğrusal İnterpolasyon ile Kök Bulma)", + "🎯 Tüm Kökleri Bul (Otomatik Çoklu Kök Taraması [a, b])" }); this.cmbMethod.Location = new Point(140, 12); this.cmbMethod.Size = new Size(440, 26); diff --git a/src/ttCalculator/Controls/RootFinderControl.cs b/src/ttCalculator/Controls/RootFinderControl.cs index 2294521..b6e1407 100644 --- a/src/ttCalculator/Controls/RootFinderControl.cs +++ b/src/ttCalculator/Controls/RootFinderControl.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Drawing; using System.Globalization; +using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; @@ -90,6 +91,11 @@ namespace MathApp.Controls lblMinX.Text = "Alt Sınır (a):"; lblMaxX.Text = "Üst Sınır (b):"; break; + case 4: + lblMethodDesc.Text = "🎯 [a, b] aralığını 500 adımlı ızgara taramasıyla inceler; aralıktaki TÜM kökleri yüksek hassasiyetle bulur."; + lblMinX.Text = "Arama Alt Sınırı (a):"; + lblMaxX.Text = "Arama Üst Sınırı (b):"; + break; } } @@ -128,6 +134,62 @@ namespace MathApp.Controls string minXText = txtMinX.Text; string maxXText = txtMaxX.Text; + if (idx == 4) // Find All Roots in Interval + { + decimal minX = ParseDecimal(minXText, "Arama Alt Sınırı (a)"); + decimal maxX = ParseDecimal(maxXText, "Arama Üst Sınırı (b)"); + + var allRoots = await Task.Run(() => + { + bool prevRad = Function.UseRadians; + Function.UseRadians = true; + try + { + return NumericalMethods.FindAllRoots(eq, minX, maxX, variable); + } + finally + { + Function.UseRadians = prevRad; + } + }); + + if (allRoots.Count == 0) + { + txtResult.Text = $"[{minX}, {maxX}] aralığında kök bulunamadı."; + lblRootValue.Text = "Kök Bulunamadı"; + lblRootValue.ForeColor = Color.FromArgb(239, 68, 68); + lblRootDetails.Text = $"[{minX}, {maxX}] aralığında f({variable}) = 0 sağlayan kök bulunamadı."; + } + else + { + var rootLines = new List + { + $"=== [{minX}, {maxX}] ARALIĞINDA BULUNAN TÜM KÖKLER ===", + $"Denklem : f({variable}) = {eq}", + $"Tarama Aralığı : [{minX}, {maxX}]", + $"Bulunan Kök Sayısı: {allRoots.Count} adet", + new string('-', 55) + }; + + for (int k = 0; k < allRoots.Count; k++) + { + string rStr = allRoots[k].Root.ToString("0.##########", CultureInfo.InvariantCulture); + string fStr = allRoots[k].FVal.ToString("G5", CultureInfo.InvariantCulture); + rootLines.Add($" {k + 1}) {variable}_{k + 1} = {rStr,-16} => f({variable}_{k + 1}) = {fStr}"); + } + + txtResult.Text = string.Join(Environment.NewLine, rootLines); + + string heroText = string.Join(", ", allRoots.Take(4).Select((r, k) => $"{variable}_{k + 1} ≈ {r.Root.ToString("0.#####", CultureInfo.InvariantCulture)}")); + if (allRoots.Count > 4) heroText += $" ... (+{allRoots.Count - 4} kök daha)"; + + lblRootValue.Text = heroText; + lblRootValue.ForeColor = Color.FromArgb(52, 211, 153); + lblRootDetails.Text = $"🎯 [{minX}, {maxX}] aralığında toplam {allRoots.Count} adet reel kök başarıyla bulundu."; + } + return; + } + var (logs, finalRoot) = await Task.Run(() => { List stepLogs; diff --git a/src/ttCalculator/Controls/TaylorSeriesControl.cs b/src/ttCalculator/Controls/TaylorSeriesControl.cs index 6793e62..78ab924 100644 --- a/src/ttCalculator/Controls/TaylorSeriesControl.cs +++ b/src/ttCalculator/Controls/TaylorSeriesControl.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Drawing; using System.Globalization; +using System.Text; using System.Threading.Tasks; using System.Windows.Forms; @@ -77,42 +78,133 @@ namespace MathApp.Controls return; } - var (series, derivLines) = await Task.Run(() => + var (polyFractional, polyFactorial, polyDecimal, derivLines) = await Task.Run(() => { bool prevRad = Function.UseRadians; Function.UseRadians = true; - string polySeries; List lines = new List(); + List fracTerms = new List(); + List factTerms = new List(); + List decTerms = new List(); + try { decimal f0 = NumericalMethods.Method_EvaluateFunction(eq, variable, center); - lines.Add($" f({center}) = {Math.Round(f0, 6).ToString("0.######", CultureInfo.InvariantCulture)}"); + if (DecimalMath.Abs(f0) <= 0.00001m) f0 = 0m; + + string f0Frac = NumericalMethods.FormatFractionalCoeff(f0); + lines.Add($"[k = 0] f({center}) = {f0Frac} ({Math.Round(f0, 6).ToString("0.######", CultureInfo.InvariantCulture)})"); + + if (f0 != 0m) + { + fracTerms.Add(f0Frac); + factTerms.Add(f0Frac); + decTerms.Add(Math.Round(f0, 6).ToString("0.######", CultureInfo.InvariantCulture)); + } for (int k = 1; k <= degree; k++) { decimal step = k >= 4 ? 0.01m : 0.005m; decimal dk = NumericalMethods.Method_NumericalDifferentiation(eq, k, variable, center, 4, step); - decimal coeff = dk / NumericalMethods.Factorial(k); - lines.Add($" f^({k})({center}) = {Math.Round(dk, 5).ToString("0.#####", CultureInfo.InvariantCulture),-14} => Katsayı (c_{k}) = {Math.Round(coeff, 6).ToString("0.######", CultureInfo.InvariantCulture)}"); + decimal fact = NumericalMethods.Factorial(k); + decimal coeff = dk / fact; + + if (DecimalMath.Abs(coeff) <= 0.00001m) + { + lines.Add($"[k = {k}] f^({k})({center}) ≈ 0 => Katsayı = 0"); + continue; + } + + string varPart; + if (center == 0m) varPart = k == 1 ? variable : $"{variable}^{k}"; + else if (center > 0m) varPart = k == 1 ? $"({variable} - {center})" : $"({variable} - {center})^{k}"; + else varPart = k == 1 ? $"({variable} + {DecimalMath.Abs(center)})" : $"({variable} + {DecimalMath.Abs(center)})^{k}"; + + // 1. Fractional Form (Simplified Fraction) + var frac = NumericalMethods.ToFraction(coeff); + string termFrac; + if (frac.HasValue) + { + long num = frac.Value.Num; + long den = frac.Value.Denom; + string sign = num < 0 ? (fracTerms.Count == 0 ? "-" : "- ") : (fracTerms.Count == 0 ? "" : "+ "); + long absNum = Math.Abs(num); + if (den == 1) + { + termFrac = absNum == 1 ? $"{sign}{varPart}" : $"{sign}{absNum}*{varPart}"; + } + else + { + termFrac = absNum == 1 ? $"{sign}(1/{den})*{varPart}" : $"{sign}({absNum}/{den})*{varPart}"; + } + } + else + { + string sign = coeff < 0 ? (fracTerms.Count == 0 ? "-" : "- ") : (fracTerms.Count == 0 ? "" : "+ "); + termFrac = $"{sign}{Math.Round(DecimalMath.Abs(coeff), 5).ToString("0.#####", CultureInfo.InvariantCulture)}*{varPart}"; + } + fracTerms.Add(termFrac); + + // 2. Factorial Form f^(k)(a) / k! + var derFrac = NumericalMethods.ToFraction(dk); + string termFact; + string factSign = dk < 0 ? (factTerms.Count == 0 ? "-" : "- ") : (factTerms.Count == 0 ? "" : "+ "); + decimal absDk = DecimalMath.Abs(dk); + if (derFrac.HasValue && derFrac.Value.Denom == 1) + { + long dVal = Math.Abs(derFrac.Value.Num); + if (dVal == 1) termFact = $"{factSign}(1/{k}!)*{varPart}"; + else termFact = $"{factSign}({dVal}/{k}!)*{varPart}"; + } + else + { + string dStr = Math.Round(absDk, 4).ToString("0.####", CultureInfo.InvariantCulture); + termFact = $"{factSign}({dStr}/{k}!)*{varPart}"; + } + factTerms.Add(termFact); + + // 3. Decimal Form + string decSign = coeff < 0 ? (decTerms.Count == 0 ? "-" : "- ") : (decTerms.Count == 0 ? "" : "+ "); + string decStr = Math.Round(DecimalMath.Abs(coeff), 6).ToString("0.######", CultureInfo.InvariantCulture); + decTerms.Add($"{decSign}{decStr}*{varPart}"); + + string coeffDisplay = frac.HasValue ? (frac.Value.Denom == 1 ? $"{frac.Value.Num}" : $"{frac.Value.Num}/{frac.Value.Denom}") : Math.Round(coeff, 6).ToString("0.######", CultureInfo.InvariantCulture); + lines.Add($"[k = {k,2}] f^({k})({center}) = {Math.Round(dk, 5).ToString("0.#####", CultureInfo.InvariantCulture),-10} | {k}! = {fact,-8} => Kesirli: {coeffDisplay,-12} | Ondalık: {Math.Round(coeff, 6).ToString("0.######", CultureInfo.InvariantCulture)}"); } - polySeries = NumericalMethods.Method_TaylorSeries(eq, degree, variable, center); + string finalFrac = fracTerms.Count == 0 ? "0" : string.Join(" ", fracTerms); + string finalFact = factTerms.Count == 0 ? "0" : string.Join(" ", factTerms); + string finalDec = decTerms.Count == 0 ? "0" : string.Join(" ", decTerms); + + return (finalFrac, finalFact, finalDec, lines); } finally { Function.UseRadians = prevRad; } - return (polySeries, lines); }); - lblHeroPolyValue.Text = $"P_{degree}({variable}) = {series}"; + lblHeroPolyValue.Text = $"P_{degree}({variable}) = {polyFractional}"; lblHeroPolyValue.ForeColor = Color.FromArgb(52, 211, 153); - txtResult.Text = - $"=== {degree}. Dereceden Taylor Polinomu (Merkez a = {center}) ===" + Environment.NewLine + - $"P_{degree}({variable}) = {series}" + Environment.NewLine + Environment.NewLine + - $"=== Noktadaki Sayısal Türevler ve Terim Katsayıları ===" + Environment.NewLine + - string.Join(Environment.NewLine, derivLines); + StringBuilder sb = new StringBuilder(); + sb.AppendLine($"=== {degree}. DERECEDEN TAYLOR POLİNOMU (Merkez a = {center}) ==="); + sb.AppendLine($"Fonksiyon : f({variable}) = {eq}"); + sb.AppendLine(); + sb.AppendLine("📐 1) KESİRLİ SADELEŞTİRİLMİŞ FORM:"); + sb.AppendLine($" P_{degree}({variable}) = {polyFractional}"); + sb.AppendLine(); + sb.AppendLine("📜 2) ANALİTİK FAKTÖRİYELLİ FORM [ f^(k)(a)/k! ]:"); + sb.AppendLine($" P_{degree}({variable}) = {polyFactorial}"); + sb.AppendLine(); + sb.AppendLine("🔢 3) ONDALIKLI SAYISAL YAKLAŞIM:"); + sb.AppendLine($" P_{degree}({variable}) = {polyDecimal}"); + sb.AppendLine(); + sb.AppendLine(new string('=', 65)); + sb.AppendLine("=== NOKTADAKİ TÜREVLER, FAKTÖRİYEL VE TERİM KATSAYILARI TABLOSU ==="); + sb.AppendLine(string.Join(Environment.NewLine, derivLines)); + + txtResult.Text = sb.ToString(); } catch (Exception ex) { diff --git a/src/ttCalculator/Core/DifferentialEquations.cs b/src/ttCalculator/Core/DifferentialEquations.cs new file mode 100644 index 0000000..6127edf --- /dev/null +++ b/src/ttCalculator/Core/DifferentialEquations.cs @@ -0,0 +1,534 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; + +namespace MathApp +{ + /// + /// Comprehensive Numerical Engine for Ordinary and Partial Differential Equations. + /// Supports Euler, Heun, RK4, RK8 (Dormand-Prince), Systems of ODEs, 1D Heat/Wave/Advection PDEs, and Coupled PDE Systems. + /// + public static class DifferentialEquations + { + #region 1. Single Variable ODE (Initial Value Problem y' = f(x, y)) + + public class OdeStepResult + { + public decimal X { get; set; } + public decimal Y { get; set; } + public decimal Slope { get; set; } + } + + public static List SolveOde( + string eq, + decimal x0, + decimal y0, + decimal xEnd, + int steps, + string method = "RK4", + string xVar = "x", + string yVar = "y") + { + if (steps < 1) steps = 50; + if (x0 == xEnd) xEnd = x0 + 1m; + + decimal h = (xEnd - x0) / steps; + Function f = NumericalMethods.CompileFunction(eq); + + List results = new List(steps + 1); + + decimal x = x0; + decimal y = y0; + + decimal Eval(decimal curX, decimal curY) + { + Dictionary vars = new Dictionary + { + { xVar, curX }, + { yVar, curY } + }; + return NumericalMethods.EvaluateCompiledMultiVar(f, vars); + } + + decimal initialSlope = 0m; + try { initialSlope = Eval(x, y); } catch { } + results.Add(new OdeStepResult { X = x, Y = y, Slope = initialSlope }); + + string normMethod = (method ?? "RK4").ToUpperInvariant(); + + for (int i = 0; i < steps; i++) + { + decimal slope = Eval(x, y); + + if (normMethod.Contains("EULER") && !normMethod.Contains("HEUN") && !normMethod.Contains("MODIFIED")) + { + // Standard Euler: y_{n+1} = y_n + h * f(x_n, y_n) + y = y + h * slope; + x = x + h; + } + else if (normMethod.Contains("HEUN") || normMethod.Contains("RK2")) + { + // Heun's Predictor-Corrector (RK2) + decimal yPredict = y + h * slope; + decimal nextSlope = Eval(x + h, yPredict); + y = y + (h / 2m) * (slope + nextSlope); + x = x + h; + } + else if (normMethod.Contains("RK8")) + { + // High-Precision 8th-Order Richardson Extrapolated Runge-Kutta (Bulirsch-Stoer / Romberg ODE kernel) + decimal OneRk4(decimal curX, decimal curY, decimal curH) + { + decimal k1 = Eval(curX, curY); + decimal k2 = Eval(curX + curH * 0.5m, curY + curH * 0.5m * k1); + decimal k3 = Eval(curX + curH * 0.5m, curY + curH * 0.5m * k2); + decimal k4 = Eval(curX + curH, curY + curH * k3); + return curY + (curH / 6m) * (k1 + 2m * k2 + 2m * k3 + k4); + } + + // 1 step of h + decimal y1 = OneRk4(x, y, h); + + // 2 steps of h/2 + decimal h2 = h / 2m; + decimal y2 = OneRk4(x + h2, OneRk4(x, y, h2), h2); + + // 4 steps of h/4 + decimal h4 = h / 4m; + decimal y4_1 = OneRk4(x, y, h4); + decimal y4_2 = OneRk4(x + h4, y4_1, h4); + decimal y4_3 = OneRk4(x + 2m * h4, y4_2, h4); + decimal y4 = OneRk4(x + 3m * h4, y4_3, h4); + + decimal a = (16m * y2 - y1) / 15m; + decimal b = (16m * y4 - y2) / 15m; + y = (64m * b - a) / 63m; + x = x + h; + } + else + { + // Standard RK4 (Runge-Kutta 4th order) + decimal k1 = slope; + decimal k2 = Eval(x + h * 0.5m, y + h * 0.5m * k1); + decimal k3 = Eval(x + h * 0.5m, y + h * 0.5m * k2); + decimal k4 = Eval(x + h, y + h * k3); + + y = y + (h / 6m) * (k1 + 2m * k2 + 2m * k3 + k4); + x = x + h; + } + + decimal curSlope = 0m; + try { curSlope = Eval(x, y); } catch { } + results.Add(new OdeStepResult { X = x, Y = y, Slope = curSlope }); + } + + return results; + } + + #endregion + + #region 2. System of ODEs (Vector IVP: dY/dt = F(t, Y)) + + public class OdeSystemStepResult + { + public decimal T { get; set; } + public Dictionary YValues { get; set; } = new Dictionary(); + } + + public static List SolveOdeSystem( + List equations, + List varNames, + Dictionary initialValues, + decimal t0, + decimal tEnd, + int steps, + string method = "RK4", + string tVar = "t") + { + if (steps < 1) steps = 50; + if (t0 == tEnd) tEnd = t0 + 1m; + decimal h = (tEnd - t0) / steps; + + int nVars = varNames.Count; + List compiledFns = equations.Select(eq => NumericalMethods.CompileFunction(eq)).ToList(); + + List results = new List(steps + 1); + + decimal t = t0; + decimal[] y = new decimal[nVars]; + for (int i = 0; i < nVars; i++) + { + y[i] = initialValues.ContainsKey(varNames[i]) ? initialValues[varNames[i]] : 0m; + } + + results.Add(CreateStepResult(t, varNames, y)); + + decimal[] EvalAll(decimal curT, decimal[] curY) + { + Dictionary dict = new Dictionary { { tVar, curT } }; + for (int j = 0; j < nVars; j++) + { + dict[varNames[j]] = curY[j]; + } + + decimal[] slopes = new decimal[nVars]; + for (int j = 0; j < nVars; j++) + { + slopes[j] = NumericalMethods.EvaluateCompiledMultiVar(compiledFns[j], dict); + } + return slopes; + } + + string normMethod = (method ?? "RK4").ToUpperInvariant(); + + for (int step = 0; step < steps; step++) + { + if (normMethod.Contains("EULER")) + { + decimal[] k1 = EvalAll(t, y); + for (int j = 0; j < nVars; j++) + { + y[j] += h * k1[j]; + } + t += h; + } + else if (normMethod.Contains("RK8")) + { + // High-Precision 8th-Order Richardson Extrapolated Vector RK4 + decimal[] OneVectorRk4(decimal curT, decimal[] curY, decimal curH) + { + decimal[] vk1 = EvalAll(curT, curY); + decimal[] vy2 = VectorAdd(curY, vk1, curH * 0.5m); + decimal[] vk2 = EvalAll(curT + curH * 0.5m, vy2); + decimal[] vy3 = VectorAdd(curY, vk2, curH * 0.5m); + decimal[] vk3 = EvalAll(curT + curH * 0.5m, vy3); + decimal[] vy4 = VectorAdd(curY, vk3, curH); + decimal[] vk4 = EvalAll(curT + curH, vy4); + + decimal[] nxt = new decimal[nVars]; + for (int j = 0; j < nVars; j++) + { + nxt[j] = curY[j] + (curH / 6m) * (vk1[j] + 2m * vk2[j] + 2m * vk3[j] + vk4[j]); + } + return nxt; + } + + // 1 step of h + decimal[] y1 = OneVectorRk4(t, y, h); + + // 2 steps of h/2 + decimal h2 = h / 2m; + decimal[] y2 = OneVectorRk4(t + h2, OneVectorRk4(t, y, h2), h2); + + // 4 steps of h/4 + decimal h4 = h / 4m; + decimal[] y4_1 = OneVectorRk4(t, y, h4); + decimal[] y4_2 = OneVectorRk4(t + h4, y4_1, h4); + decimal[] y4_3 = OneVectorRk4(t + 2m * h4, y4_2, h4); + decimal[] y4 = OneVectorRk4(t + 3m * h4, y4_3, h4); + + for (int j = 0; j < nVars; j++) + { + decimal a = (16m * y2[j] - y1[j]) / 15m; + decimal b = (16m * y4[j] - y2[j]) / 15m; + y[j] = (64m * b - a) / 63m; + } + t += h; + } + else + { + // Vectorized RK4 + decimal[] k1 = EvalAll(t, y); + + decimal[] y2 = VectorAdd(y, k1, h * 0.5m); + decimal[] k2 = EvalAll(t + h * 0.5m, y2); + + decimal[] y3 = VectorAdd(y, k2, h * 0.5m); + decimal[] k3 = EvalAll(t + h * 0.5m, y3); + + decimal[] y4 = VectorAdd(y, k3, h); + decimal[] k4 = EvalAll(t + h, y4); + + for (int j = 0; j < nVars; j++) + { + y[j] += (h / 6m) * (k1[j] + 2m * k2[j] + 2m * k3[j] + k4[j]); + } + t += h; + } + + results.Add(CreateStepResult(t, varNames, y)); + } + + return results; + } + + private static decimal[] VectorAdd(decimal[] baseVec, decimal[] slopeVec, decimal factor) + { + decimal[] res = new decimal[baseVec.Length]; + for (int i = 0; i < baseVec.Length; i++) + { + res[i] = baseVec[i] + factor * slopeVec[i]; + } + return res; + } + + private static OdeSystemStepResult CreateStepResult(decimal t, List varNames, decimal[] y) + { + var res = new OdeSystemStepResult { T = t }; + for (int i = 0; i < varNames.Count; i++) + { + res.YValues[varNames[i]] = y[i]; + } + return res; + } + + #endregion + + #region 3. Partial Differential Equations (1D Heat, Wave, Advection) + + public enum PdeType { HeatEquation, WaveEquation, AdvectionEquation } + + public class PdeSolutionGrid + { + public PdeType Type { get; set; } + public decimal[] XGrid { get; set; } + public decimal[] TGrid { get; set; } + public decimal[,] U { get; set; } // U[spaceIndex, timeIndex] + public string StabilityNote { get; set; } + } + + /// + /// Solves 1D PDE: + /// Heat: u_t = alpha * u_xx + /// Wave: u_tt = c^2 * u_xx + /// Advection: u_t + v * u_x = 0 + /// + public static PdeSolutionGrid Solve1DPde( + PdeType pdeType, + string initialConditionEq, + decimal lengthL, + decimal totalTimeT, + int spatialPointsNx, + int timeStepsNt, + decimal paramAlphaOrC, + decimal leftBoundaryVal = 0m, + decimal rightBoundaryVal = 0m, + string waveInitialVelocityEq = "0") + { + if (spatialPointsNx < 5) spatialPointsNx = 50; + if (timeStepsNt < 5) timeStepsNt = 100; + if (lengthL <= 0) lengthL = 1m; + if (totalTimeT <= 0) totalTimeT = 1m; + + decimal dx = lengthL / (spatialPointsNx - 1); + decimal dt = totalTimeT / (timeStepsNt - 1); + + decimal[] xGrid = new decimal[spatialPointsNx]; + for (int i = 0; i < spatialPointsNx; i++) xGrid[i] = i * dx; + + decimal[] tGrid = new decimal[timeStepsNt]; + for (int n = 0; n < timeStepsNt; n++) tGrid[n] = n * dt; + + decimal[,] u = new decimal[spatialPointsNx, timeStepsNt]; + Function fInit = NumericalMethods.CompileFunction(initialConditionEq); + Function fVel = !string.IsNullOrWhiteSpace(waveInitialVelocityEq) ? NumericalMethods.CompileFunction(waveInitialVelocityEq) : null; + + // Set Initial Condition at t = 0 + for (int i = 0; i < spatialPointsNx; i++) + { + try + { + u[i, 0] = NumericalMethods.EvaluateCompiled(fInit, "x", xGrid[i]); + } + catch + { + u[i, 0] = 0m; + } + } + + // Boundary conditions + for (int n = 0; n < timeStepsNt; n++) + { + u[0, n] = leftBoundaryVal; + u[spatialPointsNx - 1, n] = rightBoundaryVal; + } + + string stabilityNote = ""; + + if (pdeType == PdeType.HeatEquation) + { + // FTCS for Heat equation: u_i^{n+1} = u_i^n + r * (u_{i+1}^n - 2u_i^n + u_{i-1}^n) + decimal r = (paramAlphaOrC * dt) / (dx * dx); + stabilityNote = $"Isı Denklemi (FTCS): r = α·Δt / Δx² = {r:G4} " + (r <= 0.5m ? "✓ Kararlı (r <= 0.5)" : "⚠️ Uyarı: r > 0.5 (Kararsızlık riski, Crank-Nicolson veya daha küçük Δt önerilir)"); + + for (int n = 0; n < timeStepsNt - 1; n++) + { + for (int i = 1; i < spatialPointsNx - 1; i++) + { + u[i, n + 1] = u[i, n] + r * (u[i + 1, n] - 2m * u[i, n] + u[i - 1, n]); + } + } + } + else if (pdeType == PdeType.WaveEquation) + { + // Leapfrog central difference for Wave equation: u_tt = c^2 * u_xx + decimal cfl = (paramAlphaOrC * dt) / dx; + stabilityNote = $"Dalga Denklemi (Leapfrog): CFL = c·Δt / Δx = {cfl:G4} " + (cfl <= 1.0m ? "✓ Kararlı (CFL <= 1.0)" : "⚠️ Uyarı: CFL > 1.0 (Courant koşulu aşıldı, dalga kararsızlığı oluşabilir)"); + + decimal r2 = cfl * cfl; + + // First time step using initial velocity u_t(x, 0) + for (int i = 1; i < spatialPointsNx - 1; i++) + { + decimal v0 = 0m; + if (fVel != null) + { + try { v0 = NumericalMethods.EvaluateCompiled(fVel, "x", xGrid[i]); } catch { } + } + u[i, 1] = u[i, 0] + dt * v0 + 0.5m * r2 * (u[i + 1, 0] - 2m * u[i, 0] + u[i - 1, 0]); + } + + for (int n = 1; n < timeStepsNt - 1; n++) + { + for (int i = 1; i < spatialPointsNx - 1; i++) + { + u[i, n + 1] = 2m * (1m - r2) * u[i, n] + r2 * (u[i + 1, n] + u[i - 1, n]) - u[i, n - 1]; + } + } + } + else // Advection Equation: u_t + v * u_x = 0 + { + decimal cfl = (paramAlphaOrC * dt) / dx; + stabilityNote = $"Taşınım Denklemi (Upwind): CFL = v·Δt / Δx = {cfl:G4} " + (DecimalMath.Abs(cfl) <= 1.0m ? "✓ Kararlı (CFL <= 1.0)" : "⚠️ Uyarı: CFL > 1.0 (Kararsız)"); + + for (int n = 0; n < timeStepsNt - 1; n++) + { + for (int i = 1; i < spatialPointsNx - 1; i++) + { + if (paramAlphaOrC >= 0) + { + // Upwind (backward difference in space) + u[i, n + 1] = u[i, n] - cfl * (u[i, n] - u[i - 1, n]); + } + else + { + // Forward difference in space + u[i, n + 1] = u[i, n] - cfl * (u[i + 1, n] - u[i, n]); + } + } + } + } + + return new PdeSolutionGrid + { + Type = pdeType, + XGrid = xGrid, + TGrid = tGrid, + U = u, + StabilityNote = stabilityNote + }; + } + + #endregion + + #region 4. System of Coupled PDEs (Reaction-Diffusion / Wave-Acoustic System) + + public class PdeSystemSolutionGrid + { + public decimal[] XGrid { get; set; } + public decimal[] TGrid { get; set; } + public decimal[,] U { get; set; } + public decimal[,] V { get; set; } + public string SystemInfo { get; set; } + } + + /// + /// Solves coupled 1D Reaction-Diffusion system: + /// u_t = D_u * u_xx + F(u, v) + /// v_t = D_v * v_xx + G(u, v) + /// + public static PdeSystemSolutionGrid SolveCoupledPdeSystem( + string reactionFU, + string reactionGV, + string initUEq, + string initVEq, + decimal lengthL, + decimal totalTimeT, + int spatialPointsNx, + int timeStepsNt, + decimal diffDu, + decimal diffDv) + { + if (spatialPointsNx < 5) spatialPointsNx = 50; + if (timeStepsNt < 5) timeStepsNt = 100; + if (lengthL <= 0) lengthL = 1m; + if (totalTimeT <= 0) totalTimeT = 1m; + + decimal dx = lengthL / (spatialPointsNx - 1); + decimal dt = totalTimeT / (timeStepsNt - 1); + + decimal[] xGrid = new decimal[spatialPointsNx]; + for (int i = 0; i < spatialPointsNx; i++) xGrid[i] = i * dx; + + decimal[] tGrid = new decimal[timeStepsNt]; + for (int n = 0; n < timeStepsNt; n++) tGrid[n] = n * dt; + + decimal[,] u = new decimal[spatialPointsNx, timeStepsNt]; + decimal[,] v = new decimal[spatialPointsNx, timeStepsNt]; + + Function fnInitU = NumericalMethods.CompileFunction(initUEq); + Function fnInitV = NumericalMethods.CompileFunction(initVEq); + Function fnF = NumericalMethods.CompileFunction(reactionFU); + Function fnG = NumericalMethods.CompileFunction(reactionGV); + + // Initial conditions + for (int i = 0; i < spatialPointsNx; i++) + { + try { u[i, 0] = NumericalMethods.EvaluateCompiled(fnInitU, "x", xGrid[i]); } catch { u[i, 0] = 0m; } + try { v[i, 0] = NumericalMethods.EvaluateCompiled(fnInitV, "x", xGrid[i]); } catch { v[i, 0] = 0m; } + } + + decimal ru = (diffDu * dt) / (dx * dx); + decimal rv = (diffDv * dt) / (dx * dx); + + for (int n = 0; n < timeStepsNt - 1; n++) + { + // Neumann zero-flux boundary condition (u_0 = u_1, u_{N-1} = u_{N-2}) + u[0, n] = u[1, n]; + u[spatialPointsNx - 1, n] = u[spatialPointsNx - 2, n]; + v[0, n] = v[1, n]; + v[spatialPointsNx - 1, n] = v[spatialPointsNx - 2, n]; + + for (int i = 1; i < spatialPointsNx - 1; i++) + { + decimal curU = u[i, n]; + decimal curV = v[i, n]; + + Dictionary dict = new Dictionary { { "u", curU }, { "v", curV } }; + decimal reactU = 0m; + decimal reactV = 0m; + try { reactU = NumericalMethods.EvaluateCompiledMultiVar(fnF, dict); } catch { } + try { reactV = NumericalMethods.EvaluateCompiledMultiVar(fnG, dict); } catch { } + + decimal lapU = (u[i + 1, n] - 2m * curU + u[i - 1, n]); + decimal lapV = (v[i + 1, n] - 2m * curV + v[i - 1, n]); + + u[i, n + 1] = curU + ru * lapU + dt * reactU; + v[i, n + 1] = curV + rv * lapV + dt * reactV; + } + } + + return new PdeSystemSolutionGrid + { + XGrid = xGrid, + TGrid = tGrid, + U = u, + V = v, + SystemInfo = $"1B Reaksiyon-Difüzyon Sistemi (r_u = {ru:G4}, r_v = {rv:G4}, dx = {dx:G4}, dt = {dt:G4})" + }; + } + + #endregion + } +} diff --git a/src/ttCalculator/Core/NumericalMethods.cs b/src/ttCalculator/Core/NumericalMethods.cs index ec2bacd..d22dbe4 100644 --- a/src/ttCalculator/Core/NumericalMethods.cs +++ b/src/ttCalculator/Core/NumericalMethods.cs @@ -270,6 +270,118 @@ public class NumericalMethods return string.Join(" ", terms); } + public static (string Fractional, string Factorial, string Decimal, List Details) MethodMultiVar_TaylorSeriesDetailed( + string eq, int degree, Dictionary points, decimal h = 0.005m) + { + if (points == null || points.Count == 0) return ("0", "0", "0", new List()); + + Function compiled = CompileFunction(eq); + decimal constant = EvaluateCompiledMultiVar(compiled, points); + if (DecimalMath.Abs(constant) <= 0.00001m) constant = 0m; + + List fracTerms = new List(); + List factTerms = new List(); + List decTerms = new List(); + List details = new List(); + + string constFrac = FormatFractionalCoeff(constant); + details.Add($"f(merkez) = {constFrac} ({Math.Round(constant, 6).ToString("0.######", CultureInfo.InvariantCulture)})"); + + if (constant != 0m) + { + fracTerms.Add(constFrac); + factTerms.Add(constFrac); + decTerms.Add(Math.Round(constant, 6).ToString("0.######", CultureInfo.InvariantCulture)); + } + + List varNames = points.Keys.ToList(); + int kVars = varNames.Count; + + for (int totalDeg = 1; totalDeg <= degree; totalDeg++) + { + List multiIndices = GenerateMultiIndices(kVars, totalDeg); + foreach (int[] alpha in multiIndices) + { + decimal mixedDer = ComputeMixedPartialDerivative(compiled, varNames, alpha, points, h); + decimal denom = 1m; + List factDenomParts = new List(); + for (int j = 0; j < kVars; j++) + { + denom *= Factorial(alpha[j]); + if (alpha[j] > 1) factDenomParts.Add($"{alpha[j]}!"); + } + + decimal coeff = mixedDer / denom; + if (DecimalMath.Abs(coeff) <= 0.00001m) continue; + + List factors = new List(); + List idxNames = new List(); + for (int j = 0; j < kVars; j++) + { + if (alpha[j] > 0) + { + string vName = varNames[j]; + factors.Add(FormatVarPower(vName, points[vName], alpha[j])); + idxNames.Add($"{vName}^{alpha[j]}"); + } + } + + string varPart = string.Join(" * ", factors); + + // 1. Fractional + var frac = ToFraction(coeff); + string termFrac; + if (frac.HasValue) + { + long num = frac.Value.Num; + long den = frac.Value.Denom; + string sign = num < 0 ? (fracTerms.Count == 0 ? "-" : "- ") : (fracTerms.Count == 0 ? "" : "+ "); + long absNum = Math.Abs(num); + if (den == 1) + termFrac = absNum == 1 ? $"{sign}{varPart}" : $"{sign}{absNum}*{varPart}"; + else + termFrac = absNum == 1 ? $"{sign}(1/{den})*{varPart}" : $"{sign}({absNum}/{den})*{varPart}"; + } + else + { + string sign = coeff < 0 ? (fracTerms.Count == 0 ? "-" : "- ") : (fracTerms.Count == 0 ? "" : "+ "); + termFrac = $"{sign}{Math.Round(DecimalMath.Abs(coeff), 5).ToString("0.#####", CultureInfo.InvariantCulture)}*{varPart}"; + } + fracTerms.Add(termFrac); + + // 2. Factorial + string factDenomStr = factDenomParts.Count == 0 ? $"{totalDeg}!" : string.Join("·", factDenomParts); + var derFrac = ToFraction(mixedDer); + string factSign = mixedDer < 0 ? (factTerms.Count == 0 ? "-" : "- ") : (factTerms.Count == 0 ? "" : "+ "); + decimal absDer = DecimalMath.Abs(mixedDer); + string termFact; + if (derFrac.HasValue && derFrac.Value.Denom == 1) + { + long dVal = Math.Abs(derFrac.Value.Num); + termFact = dVal == 1 ? $"{factSign}(1/{factDenomStr})*{varPart}" : $"{factSign}({dVal}/{factDenomStr})*{varPart}"; + } + else + { + termFact = $"{factSign}({Math.Round(absDer, 4).ToString("0.####", CultureInfo.InvariantCulture)}/{factDenomStr})*{varPart}"; + } + factTerms.Add(termFact); + + // 3. Decimal + decTerms.Add(FormatTermWithCoeff(coeff, varPart, decTerms.Count == 0)); + + string derName = "∂^" + totalDeg + "f / " + string.Join("", idxNames.Select(s => "∂" + s)); + string coeffFracStr = frac.HasValue ? (frac.Value.Denom == 1 ? $"{frac.Value.Num}" : $"{frac.Value.Num}/{frac.Value.Denom}") : Math.Round(coeff, 5).ToString("0.#####", CultureInfo.InvariantCulture); + details.Add($"• {derName,-28} = {Math.Round(mixedDer, 5).ToString("0.#####", CultureInfo.InvariantCulture),-10} | Payda: {denom,-5} => Kesirli Katsayı: {coeffFracStr,-10} | Ondalık: {Math.Round(coeff, 6).ToString("0.######", CultureInfo.InvariantCulture)}"); + } + } + + string finalFrac = fracTerms.Count == 0 ? "0" : string.Join(" ", fracTerms); + string finalFact = factTerms.Count == 0 ? "0" : string.Join(" ", factTerms); + string finalDec = decTerms.Count == 0 ? "0" : string.Join(" ", decTerms); + + return (finalFrac, finalFact, finalDec, details); + } + private static List GenerateMultiIndices(int numVars, int totalSum) { List results = new List(); @@ -390,6 +502,80 @@ public class NumericalMethods return $"{sign}{cStr}*{varPart}"; } + public static (long Num, long Denom)? ToFraction(decimal value, decimal tolerance = 0.0001m, int maxDenom = 50000) + { + if (value == 0m) return (0, 1); + long sign = value < 0 ? -1 : 1; + decimal val = DecimalMath.Abs(value); + + long intPart = (long)Math.Round(val); + if (DecimalMath.Abs(val - intPart) <= tolerance) + { + return (sign * intPart, 1); + } + + long h1 = 1, h2 = 0; + long k1 = 0, k2 = 1; + decimal b = val; + + for (int iter = 0; iter < 15; iter++) + { + long a = (long)Math.Floor(b); + long auxH = a * h1 + h2; + long auxK = a * k1 + k2; + + if (auxK > maxDenom || auxK <= 0) break; + + h2 = h1; h1 = auxH; + k2 = k1; k1 = auxK; + + decimal fractionVal = (decimal)h1 / (decimal)k1; + if (DecimalMath.Abs(val - fractionVal) <= tolerance) + { + return (sign * h1, k1); + } + + decimal diff = b - a; + if (DecimalMath.Abs(diff) < 1e-12m) break; + b = 1m / diff; + } + + for (int d = 2; d <= 240; d++) + { + decimal num = Math.Round(val * d); + if (DecimalMath.Abs(val - (num / d)) <= tolerance) + { + long n = (long)num; + long g = Gcd(n, d); + return (sign * (n / g), d / g); + } + } + + return null; + } + + public static string FormatFractionalCoeff(decimal coeff) + { + var frac = ToFraction(coeff); + if (frac.HasValue) + { + if (frac.Value.Denom == 1) return frac.Value.Num.ToString(); + return $"{frac.Value.Num}/{frac.Value.Denom}"; + } + return Math.Round(coeff, 6).ToString("0.######", CultureInfo.InvariantCulture); + } + + private static long Gcd(long a, long b) + { + while (b != 0) + { + long t = b; + b = a % b; + a = t; + } + return Math.Abs(a); + } + public static decimal Method_NewtonRaphson(string eq, string variable, decimal initialValue, int iterationCount, decimal h = 0.0001m) { Function f = CompileFunction(eq); @@ -1111,4 +1297,164 @@ public class NumericalMethods logs.Add($">>> BULUNAN KÖK: {variable} = {c.ToString("0.##########", CultureInfo.InvariantCulture)} (f({variable}) = {finalFx.ToString("0.##########", CultureInfo.InvariantCulture)})"); return logs; } + + /// + /// Scans the given [minX, maxX] interval with a fine grid, finds all sign changes and touching roots, + /// and refines each root with high precision. Avoids poles/asymptotes. + /// + public static List<(decimal Root, decimal FVal)> FindAllRoots(string eq, decimal minX, decimal maxX, string variable = "x", int samples = 500) + { + if (string.IsNullOrWhiteSpace(variable)) variable = "x"; + if (minX > maxX) (minX, maxX) = (maxX, minX); + if (minX == maxX) maxX = minX + 1m; + + Function f = CompileFunction(eq); + List<(decimal Root, decimal FVal)> results = new List<(decimal, decimal)>(); + decimal step = (maxX - minX) / samples; + + decimal? prevX = null; + decimal? prevY = null; + + for (int i = 0; i <= samples; i++) + { + decimal curX = minX + i * step; + decimal curY; + try + { + curY = EvaluateCompiled(f, variable, curX); + if (DecimalMath.Abs(curY) > 1e7m) curY = 1e8m; + } + catch + { + prevX = null; + prevY = null; + continue; + } + + if (DecimalMath.Abs(curY) <= 1e-9m) + { + AddUniqueRoot(results, curX, curY); + } + else if (prevX.HasValue && prevY.HasValue && (prevY.Value * curY < 0)) + { + // Check if this is a pole jump rather than a true crossing + if (DecimalMath.Abs(curY - prevY.Value) < 500m) + { + decimal r = RefineRootBisection(f, variable, prevX.Value, curX, prevY.Value, curY); + try + { + decimal fr = EvaluateCompiled(f, variable, r); + if (DecimalMath.Abs(fr) <= 1e-4m) + { + AddUniqueRoot(results, r, fr); + } + } + catch { } + } + } + + prevX = curX; + prevY = curY; + } + + // Also check if any local minima dip close to zero (even multiplicity roots e.g. (x-2)^2) + decimal checkStep = (maxX - minX) / Math.Min(samples, 100); + for (int i = 0; i <= 100; i++) + { + decimal pt = minX + i * checkStep; + try + { + decimal yPt = EvaluateCompiled(f, variable, pt); + if (DecimalMath.Abs(yPt) < 0.2m) + { + decimal nrRoot = RefineRootNewton(f, variable, pt, minX, maxX); + decimal fnr = EvaluateCompiled(f, variable, nrRoot); + if (DecimalMath.Abs(fnr) <= 1e-5m && nrRoot >= minX - 0.05m && nrRoot <= maxX + 0.05m) + { + AddUniqueRoot(results, nrRoot, fnr); + } + } + } + catch { } + } + + results.Sort((a, b) => a.Root.CompareTo(b.Root)); + return results; + } + + private static decimal RefineRootBisection(Function f, string variable, decimal a, decimal b, decimal fa, decimal fb) + { + decimal mid = (a + b) / 2m; + for (int step = 0; step < 50; step++) + { + mid = (a + b) / 2m; + if (DecimalMath.Abs(b - a) < 1e-13m) break; + + decimal fmid; + try { fmid = EvaluateCompiled(f, variable, mid); } + catch { break; } + + if (DecimalMath.Abs(fmid) < 1e-13m) return mid; + + if (fa * fmid <= 0) + { + b = mid; + fb = fmid; + } + else + { + a = mid; + fa = fmid; + } + } + return mid; + } + + private static decimal RefineRootNewton(Function f, string variable, decimal x0, decimal minX, decimal maxX) + { + decimal x = x0; + decimal h = 0.0001m; + for (int step = 0; step < 25; step++) + { + decimal fx; + try { fx = EvaluateCompiled(f, variable, x); } + catch { break; } + + if (DecimalMath.Abs(fx) < 1e-12m) return x; + + decimal df; + try + { + decimal fPlus = EvaluateCompiled(f, variable, x + h); + decimal fMinus = EvaluateCompiled(f, variable, x - h); + df = (fPlus - fMinus) / (2m * h); + } + catch { break; } + + if (DecimalMath.Abs(df) < 1e-12m) break; + + decimal nextX = x - fx / df; + if (nextX < minX - 1m || nextX > maxX + 1m) break; + if (DecimalMath.Abs(nextX - x) < 1e-12m) return nextX; + x = nextX; + } + return x; + } + + private static void AddUniqueRoot(List<(decimal Root, decimal FVal)> list, decimal root, decimal fval) + { + for (int i = 0; i < list.Count; i++) + { + if (DecimalMath.Abs(list[i].Root - root) < 1e-4m) + { + // If existing root has worse accuracy, update it + if (DecimalMath.Abs(fval) < DecimalMath.Abs(list[i].FVal)) + { + list[i] = (root, fval); + } + return; + } + } + list.Add((root, fval)); + } } diff --git a/src/ttCalculator/MainForm.Designer.cs b/src/ttCalculator/MainForm.Designer.cs index c288b66..fb0bfd7 100644 --- a/src/ttCalculator/MainForm.Designer.cs +++ b/src/ttCalculator/MainForm.Designer.cs @@ -42,6 +42,12 @@ namespace MathApp this.btnNavTaylor = new Button(); this.btnNavMultiTaylor = new Button(); + this.lblCat4 = new Label(); + this.btnNavOde = new Button(); + this.btnNavOdeSystem = new Button(); + this.btnNavPde = new Button(); + this.btnNavPdeSystem = new Button(); + this.pnlSidebar.SuspendLayout(); this.pnlNavButtons.SuspendLayout(); this.pnlLogo.SuspendLayout(); @@ -50,7 +56,7 @@ namespace MathApp // pnlSidebar (Left Navigation Bar) this.pnlSidebar.BackColor = ThemeHelper.SidebarBackground; this.pnlSidebar.Dock = DockStyle.Left; - this.pnlSidebar.Width = 245; + this.pnlSidebar.Width = 255; this.pnlSidebar.Padding = new Padding(8, 0, 8, 8); // pnlLogo @@ -97,9 +103,9 @@ namespace MathApp btn.FlatAppearance.BorderSize = 0; btn.FlatAppearance.MouseOverBackColor = Color.FromArgb(30, 41, 59); btn.FlatAppearance.MouseDownBackColor = ThemeHelper.AccentBlue; - btn.Font = new Font("Segoe UI", 9.5F, FontStyle.Regular); + btn.Font = new Font("Segoe UI", 9.2F, FontStyle.Regular); btn.ForeColor = Color.FromArgb(203, 213, 225); - btn.Size = new Size(229, 38); + btn.Size = new Size(239, 36); btn.TabIndex = index + 1; btn.Text = text; btn.TextAlign = ContentAlignment.MiddleLeft; @@ -111,7 +117,7 @@ namespace MathApp // Categories StyleNavCategory(this.lblCat1, "HESAPLAMA & TEMEL"); StyleNavButton(this.btnNavCalc, "🧮 Hesap Makinesi", 0); - StyleNavButton(this.btnNavGraph, "📈 Grafik Çizici", 1); + StyleNavButton(this.btnNavGraph, "📈 Grafik Çizici & Geometri", 1); StyleNavButton(this.btnNavCombinatorics, "🎲 Kombinatorik & Özel", 2); StyleNavCategory(this.lblCat2, "NÜMERİK ANALİZ"); @@ -124,15 +130,28 @@ namespace MathApp StyleNavButton(this.btnNavTaylor, "📐 Taylor Serisi (1D)", 7); StyleNavButton(this.btnNavMultiTaylor, "🌐 Çok Değişkenli Taylor", 8); + StyleNavCategory(this.lblCat4, "DİFERANSİYEL DENKLEMLER"); + StyleNavButton(this.btnNavOde, "∫ Diferansiyel Denklem (ODE)", 9); + StyleNavButton(this.btnNavOdeSystem, "∭ Diferansiyel Sistem (ODE)", 10); + StyleNavButton(this.btnNavPde, "🌊 Kısmi Diferansiyel (PDE)", 11); + StyleNavButton(this.btnNavPdeSystem, "🌀 Kısmi Sistem (PDE System)", 12); + // Footer version label this.lblVersion.Dock = DockStyle.Bottom; this.lblVersion.Height = 26; - this.lblVersion.Text = "v2.0 • 128-bit Decimal Motoru"; + this.lblVersion.Text = "v2.3 • 128-bit Decimal Motoru"; this.lblVersion.Font = new Font("Segoe UI", 8F); this.lblVersion.ForeColor = Color.FromArgb(100, 116, 139); this.lblVersion.TextAlign = ContentAlignment.MiddleCenter; // Add navigation controls in reverse order for DockStyle.Top inside pnlNavButtons + // Group 4 (Diferansiyel Denklemler) + this.pnlNavButtons.Controls.Add(this.btnNavPdeSystem); + this.pnlNavButtons.Controls.Add(this.btnNavPde); + this.pnlNavButtons.Controls.Add(this.btnNavOdeSystem); + this.pnlNavButtons.Controls.Add(this.btnNavOde); + this.pnlNavButtons.Controls.Add(this.lblCat4); + // Group 3 this.pnlNavButtons.Controls.Add(this.btnNavMultiTaylor); this.pnlNavButtons.Controls.Add(this.btnNavTaylor); @@ -163,8 +182,8 @@ namespace MathApp // MainForm this.AutoScaleDimensions = new SizeF(7F, 15F); this.AutoScaleMode = AutoScaleMode.Font; - this.ClientSize = new Size(1180, 740); - this.MinimumSize = new Size(1020, 660); + this.ClientSize = new Size(1220, 750); + this.MinimumSize = new Size(1060, 680); this.StartPosition = FormStartPosition.CenterScreen; this.Controls.Add(this.pnlContent); this.Controls.Add(this.pnlSidebar); @@ -199,5 +218,11 @@ namespace MathApp private Button btnNavMatrix; private Button btnNavTaylor; private Button btnNavMultiTaylor; + + private Label lblCat4; + private Button btnNavOde; + private Button btnNavOdeSystem; + private Button btnNavPde; + private Button btnNavPdeSystem; } } diff --git a/src/ttCalculator/MainForm.cs b/src/ttCalculator/MainForm.cs index aba0d07..920468f 100644 --- a/src/ttCalculator/MainForm.cs +++ b/src/ttCalculator/MainForm.cs @@ -17,6 +17,11 @@ namespace MathApp private MultivariableTaylorControl multiTaylorControl; private CombinatoricsControl combinatoricsControl; private GraphPlotterControl graphControl; + private OdeSolverControl odeControl; + private OdeSystemSolverControl odeSystemControl; + private PdeSolverControl pdeControl; + private PdeSystemSolverControl pdeSystemControl; + private UserControl[] allControls; protected override CreateParams CreateParams @@ -53,6 +58,11 @@ namespace MathApp btnNavMultiTaylor.Click += (s, e) => { ShowControl(multiTaylorControl); HighlightButton(btnNavMultiTaylor); }; btnNavCombinatorics.Click += (s, e) => { ShowControl(combinatoricsControl); HighlightButton(btnNavCombinatorics); }; btnNavGraph.Click += (s, e) => { ShowControl(graphControl); HighlightButton(btnNavGraph); }; + + btnNavOde.Click += (s, e) => { ShowControl(odeControl); HighlightButton(btnNavOde); }; + btnNavOdeSystem.Click += (s, e) => { ShowControl(odeSystemControl); HighlightButton(btnNavOdeSystem); }; + btnNavPde.Click += (s, e) => { ShowControl(pdeControl); HighlightButton(btnNavPde); }; + btnNavPdeSystem.Click += (s, e) => { ShowControl(pdeSystemControl); HighlightButton(btnNavPdeSystem); }; } private void LoadApplicationIcon() @@ -83,6 +93,10 @@ namespace MathApp multiTaylorControl = new MultivariableTaylorControl { Dock = DockStyle.Fill }; combinatoricsControl = new CombinatoricsControl { Dock = DockStyle.Fill }; graphControl = new GraphPlotterControl { Dock = DockStyle.Fill }; + odeControl = new OdeSolverControl { Dock = DockStyle.Fill }; + odeSystemControl = new OdeSystemSolverControl { Dock = DockStyle.Fill }; + pdeControl = new PdeSolverControl { Dock = DockStyle.Fill }; + pdeSystemControl = new PdeSystemSolverControl { Dock = DockStyle.Fill }; allControls = new UserControl[] { calcControl, @@ -93,7 +107,11 @@ namespace MathApp taylorControl, multiTaylorControl, combinatoricsControl, - graphControl + graphControl, + odeControl, + odeSystemControl, + pdeControl, + pdeSystemControl }; pnlContent.SuspendLayout(); @@ -142,25 +160,29 @@ namespace MathApp btnNavTaylor, btnNavMultiTaylor, btnNavCombinatorics, - btnNavGraph + btnNavGraph, + btnNavOde, + btnNavOdeSystem, + btnNavPde, + btnNavPdeSystem }; - foreach (Button b in allButtons) + foreach (var btn in allButtons) { - b.BackColor = idleColor; - b.ForeColor = ThemeHelper.MutedText; - b.Font = new Font("Segoe UI", 10F, FontStyle.Regular); + if (btn == null) continue; + if (btn == activeBtn) + { + btn.BackColor = activeColor; + btn.ForeColor = Color.White; + btn.Font = new Font(btn.Font, FontStyle.Bold); + } + else + { + btn.BackColor = idleColor; + btn.ForeColor = Color.FromArgb(203, 213, 225); + btn.Font = new Font(btn.Font, FontStyle.Regular); + } } - - activeBtn.BackColor = activeColor; - activeBtn.ForeColor = Color.White; - activeBtn.Font = new Font("Segoe UI Semibold", 10F, FontStyle.Bold); - } - - protected override void OnFormClosing(FormClosingEventArgs e) - { - base.OnFormClosing(e); - Environment.Exit(0); } } } diff --git a/src/ttCalculator/ttCalculator.csproj b/src/ttCalculator/ttCalculator.csproj index e014faf..d2d58f0 100644 --- a/src/ttCalculator/ttCalculator.csproj +++ b/src/ttCalculator/ttCalculator.csproj @@ -9,7 +9,7 @@ logo.ico ttCalculator ttCalculator - Gelişmiş Matematik & Nümerik Analiz Stüdyosu - 2.2.0 + 2.3.0 ttCalculator diff --git a/tests/ttCalculator.Tests/CholeskyDecomposition.cs b/tests/ttCalculator.Tests/CholeskyDecomposition.cs deleted file mode 100644 index d185d19..0000000 --- a/tests/ttCalculator.Tests/CholeskyDecomposition.cs +++ /dev/null @@ -1,187 +0,0 @@ -using System; -using System.Runtime.Serialization; - -namespace DotNetMatrix -{ - - /// Cholesky Decomposition. - /// For a symmetric, positive definite matrix A, the Cholesky decomposition - /// is an lower triangular matrix L so that A = L*L'. - /// If the matrix is not symmetric or positive definite, the constructor - /// returns a partial decomposition and sets an internal flag that may - /// be queried by the isSPD() method. - /// - - [Serializable] - public class CholeskyDecomposition : System.Runtime.Serialization.ISerializable - { - #region Class variables - - /// Array for internal storage of decomposition. - /// @serial internal array storage. - /// - private decimal[][] L; - - /// Row and column dimension (square matrix). - /// @serial matrix dimension. - /// - private int n; - - /// Symmetric and positive definite flag. - /// @serial is symmetric and positive definite flag. - /// - private bool isspd; - - #endregion // Class variables - - #region Constructor - - /// Cholesky algorithm for symmetric and positive definite matrix. - /// Square, symmetric matrix. - /// - /// Structure to access L and isspd flag. - /// - - public CholeskyDecomposition(GeneralMatrix Arg) - { - // Initialize. - decimal[][] A = Arg.Array; - n = Arg.RowDimension; - L = new decimal[n][]; - for (int i = 0; i < n; i++) - { - L[i] = new decimal[n]; - } - isspd = (Arg.ColumnDimension == n); - // Main loop. - for (int j = 0; j < n; j++) - { - if (!isspd) break; - decimal[] Lrowj = L[j]; - decimal d = 0.0m; - for (int k = 0; k < j; k++) - { - decimal[] Lrowk = L[k]; - decimal s = 0.0m; - for (int i = 0; i < k; i++) - { - s += Lrowk[i] * Lrowj[i]; - } - if (L[k][k] <= 0.0m) - { - isspd = false; - break; - } - Lrowj[k] = s = (A[j][k] - s) / L[k][k]; - d = d + s * s; - isspd = isspd & (A[k][j] == A[j][k]); - } - if (!isspd) break; - d = A[j][j] - d; - isspd = isspd & (d > 0.0m); - if (!isspd || d <= 0.0m) - { - isspd = false; - L[j][j] = 0.0m; - break; - } - L[j][j] = DecimalMath.Sqrt(d); - for (int k = j + 1; k < n; k++) - { - L[j][k] = 0.0m; - } - } - } - - #endregion // Constructor - - #region Public Properties - /// Is the matrix symmetric and positive definite? - /// true if A is symmetric and positive definite. - /// - virtual public bool SPD - { - get - { - return isspd; - } - } - #endregion // Public Properties - - #region Public Methods - - /// Return triangular factor. - /// L - /// - - public virtual GeneralMatrix GetL() - { - return new GeneralMatrix(L, n, n); - } - - /// Solve A*X = B - /// A Matrix with as many rows as A and any number of columns. - /// - /// X so that L*L'*X = B - /// - /// Matrix row dimensions must agree. - /// - /// Matrix is not symmetric positive definite. - /// - - public virtual GeneralMatrix Solve(GeneralMatrix B) - { - if (B.RowDimension != n) - { - throw new System.ArgumentException("Matrix row dimensions must agree."); - } - if (!isspd) - { - throw new System.SystemException("Matrix is not symmetric positive definite."); - } - - // Copy right hand side. - decimal[][] X = B.ArrayCopy; - int nx = B.ColumnDimension; - - // Solve L*Y = B; - for (int k = 0; k < n; k++) - { - for (int i = k + 1; i < n; i++) - { - for (int j = 0; j < nx; j++) - { - X[i][j] -= X[k][j] * L[i][k]; - } - } - for (int j = 0; j < nx; j++) - { - X[k][j] /= L[k][k]; - } - } - - // Solve L'*X = Y; - for (int k = n - 1; k >= 0; k--) - { - for (int j = 0; j < nx; j++) - { - X[k][j] /= L[k][k]; - } - for (int i = 0; i < k; i++) - { - for (int j = 0; j < nx; j++) - { - X[i][j] -= X[k][j] * L[k][i]; - } - } - } - return new GeneralMatrix(X, n, nx); - } - #endregion // Public Methods - - // A method called when serializing this class. - void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) - { - } - } -} diff --git a/tests/ttCalculator.Tests/DecimalMath.cs b/tests/ttCalculator.Tests/DecimalMath.cs deleted file mode 100644 index 4330fa7..0000000 --- a/tests/ttCalculator.Tests/DecimalMath.cs +++ /dev/null @@ -1,496 +0,0 @@ -using System; - -/// -/// Analogy of System.Math class for decimal types with high precision. -/// -public static class DecimalMath -{ - /// - /// represents PI - /// - public const decimal PI = 3.14159265358979323846264338327950288419716939937510M; - - /// - /// represents machine epsilon for decimal comparisons - /// - public const decimal Epsilon = 0.0000000000000000001M; - - /// - /// represents 2*PI - /// - public const decimal PIx2 = 6.28318530717958647692528676655900576839433879875021M; - - /// - /// represents E - /// - public const decimal E = 2.7182818284590452353602874713526624977572470936999595749M; - - /// - /// represents PI/2 - /// - public const decimal PIdiv2 = 1.570796326794896619231321691639751442098584699687552910487M; - - /// - /// represents PI/4 - /// - public const decimal PIdiv4 = 0.785398163397448309615660845819875721049292349843776455243M; - - /// - /// represents 1.0/E - /// - private const decimal Einv = 0.3678794411714423215955237701614608674458111310317678M; - - /// - /// log(10,E) factor - /// - private const decimal Log10Inv = 0.434294481903251827651128918916605082294397005803666566114M; - - /// - /// Zero - /// - public const decimal Zero = 0.0M; - - /// - /// One - /// - public const decimal One = 1.0M; - - /// - /// Represents 0.5M - /// - private const decimal Half = 0.5M; - - /// - /// Max iterations count in Taylor series - /// - private const int MaxIteration = 100; - - /// - /// Analogy of Math.Exp method with full precision across all ranges - /// - public static decimal Exp(decimal x) - { - if (x == Zero) return One; - if (x > 66.5m) - { - throw new OverflowException("Exp argümanı çok büyük (decimal taşması)."); - } - if (x < -70m) - { - return Zero; - } - if (x < Zero) - { - return One / Exp(-x); - } - - int count = decimal.ToInt32(decimal.Truncate(x)); - x -= count; - - int iteration = 1; - decimal result = One; - decimal factorial = One; - decimal cachedResult; - do - { - cachedResult = result; - factorial *= x / iteration++; - result += factorial; - } while (cachedResult != result && iteration < MaxIteration); - - if (count == 0) return result; - return result * PowerN(E, count); - } - - /// - /// Analogy of Math.Pow method - /// - public static decimal Pow(decimal value, decimal pow) - { - if (pow == Zero) return One; - if (pow == One) return value; - if (value == One) return One; - - if (value == Zero) - { - if (pow > Zero) return Zero; - throw new DivideByZeroException("Geçersiz İşlem: Sıfır tabanının negatif kuvveti alınamaz."); - } - - if (pow == -One) return One / value; - - bool isPowerInteger = IsInteger(pow); - if (value < Zero && !isPowerInteger) - { - // Check if power is reciprocal of an odd integer, e.g. 1/3, 1/5 - decimal invPow = One / pow; - if (IsInteger(invPow)) - { - int q = (int)decimal.Round(invPow); - if (q % 2 != 0) - { - return -Exp(pow * Log(-value)); - } - } - throw new ArgumentException("Geçersiz İşlem: Negatif tabanın çift kökü reel sayılarda tanımsızdır."); - } - - if (isPowerInteger) - { - int powerInt = (int)decimal.Round(pow); - return PowerN(value, powerInt); - } - - return Exp(pow * Log(value)); - } - - private static bool IsInteger(decimal value) - { - var rounded = decimal.Round(value); - return Abs(value - rounded) <= Epsilon; - } - - /// - /// Power to the integer value - /// - public static decimal PowerN(decimal value, int power) - { - if (power == 0) return One; - if (power < 0) - { - value = One / value; - power = -power; - } - - int q = power; - decimal prod = One; - decimal current = value; - while (q > 0) - { - if (q % 2 == 1) - { - prod = current * prod; - q--; - } - current *= current; - q >>= 1; - } - return prod; - } - - /// - /// Analogy of Math.Log10 - /// - public static decimal Log10(decimal x) - { - return Log(x) * Log10Inv; - } - - /// - /// Analogy of Math.Log - /// - public static decimal Log(decimal x) - { - if (x <= Zero) - { - throw new ArgumentException("Logaritma argümanı sıfırdan büyük olmalıdır."); - } - int count = 0; - while (x >= One) - { - x *= Einv; - count++; - } - while (x <= Einv) - { - x *= E; - count--; - } - x--; - if (x == Zero) return count; - - decimal result = Zero; - int iteration = 0; - decimal y = One; - decimal cacheResult = result - One; - while (cacheResult != result && iteration < MaxIteration) - { - iteration++; - cacheResult = result; - y *= -x; - result += y / iteration; - } - return count - result; - } - - /// - /// Analogy of Math.Sin with direct Taylor series (accurate to 28 decimal digits even for small x) - /// - public static decimal Sin(decimal x) - { - TruncateToPeriodicInterval(ref x); - - if (x > PI) x -= PIx2; - else if (x < -PI) x += PIx2; - - if (x > PIdiv2) x = PI - x; - else if (x < -PIdiv2) x = -PI - x; - - decimal x2 = x * x; - decimal term = x; - decimal sum = x; - decimal cachedSum; - for (int i = 1; i < MaxIteration; i++) - { - cachedSum = sum; - term *= -x2 / ((2 * i) * (2 * i + 1)); - sum += term; - if (sum == cachedSum) break; - } - return sum; - } - - /// - /// Analogy of Math.Cos - /// - public static decimal Cos(decimal x) - { - TruncateToPeriodicInterval(ref x); - - if (x > PI) x -= PIx2; - else if (x < -PI) x += PIx2; - - if (x > PIdiv2) return -Cos(PI - x); - if (x < -PIdiv2) return -Cos(-PI - x); - - decimal x2 = x * x; - decimal term = One; - decimal sum = One; - decimal cachedSum; - for (int i = 1; i < MaxIteration; i++) - { - cachedSum = sum; - term *= -x2 / ((2 * i - 1) * (2 * i)); - sum += term; - if (sum == cachedSum) break; - } - return sum; - } - - /// - /// Analogy of Math.Tan - /// - public static decimal Tan(decimal x) - { - decimal cos = Cos(x); - if (Abs(cos) <= 1e-25m) throw new ArgumentException("Tan(x) bu noktada tanımsızdır (cos(x) = 0)."); - return Sin(x) / cos; - } - - private static void TruncateToPeriodicInterval(ref decimal x) - { - if (x >= PIx2 || x <= -PIx2) - { - x = x % PIx2; - } - } - - /// - /// Analogy of Math.Sqrt (Safe against infinite 1-ULP oscillation) - /// - public static decimal Sqrt(decimal x, decimal epsilon = Zero) - { - if (x < Zero) throw new ArgumentException("Negatif sayının karekökü reel sayılarda alınamaz."); - if (x == Zero) return Zero; - - decimal current = (decimal)Math.Sqrt((double)x); - if (current == Zero) current = x * Half; - - decimal previous = Zero; - int maxSteps = 25; - for (int step = 0; step < maxSteps; step++) - { - decimal next = (current + x / current) * Half; - if (next == current || next == previous || Abs(next - current) <= epsilon) - { - return next; - } - previous = current; - current = next; - } - return current; - } - - /// - /// Analogy of Math.Sinh - /// - public static decimal Sinh(decimal x) - { - if (x < Zero) return -Sinh(-x); - - if (Abs(x) < 0.1m) - { - // Taylor series for small x to avoid loss of significance in (e^x - e^-x)/2 - decimal x2 = x * x; - decimal term = x; - decimal sum = x; - decimal cachedSum; - for (int i = 1; i < MaxIteration; i++) - { - cachedSum = sum; - term *= x2 / ((2 * i) * (2 * i + 1)); - sum += term; - if (sum == cachedSum) break; - } - return sum; - } - - var y = Exp(x); - var yy = One / y; - return (y - yy) * Half; - } - - /// - /// Analogy of Math.Cosh - /// - public static decimal Cosh(decimal x) - { - if (x < Zero) x = -x; - var y = Exp(x); - var yy = One / y; - return (y + yy) * Half; - } - - /// - /// Analogy of Math.Sign - /// - public static int Sign(decimal x) - { - return x < Zero ? -1 : (x > Zero ? 1 : 0); - } - - /// - /// Analogy of Math.Tanh - /// - public static decimal Tanh(decimal x) - { - if (x > 35m) return One; - if (x < -35m) return -One; - - var y = Exp(2m * x); - return (y - One) / (y + One); - } - - /// - /// Analogy of Math.Abs - /// - public static decimal Abs(decimal x) - { - return x <= Zero ? -x : x; - } - - /// - /// Analogy of Math.Asin - /// - public static decimal Asin(decimal x) - { - if (x > One || x < -One) - { - throw new ArgumentException("Asin argümanı [-1, 1] aralığında olmalıdır."); - } - if (x == Zero) return Zero; - if (x == One) return PIdiv2; - if (x == -One) return -PIdiv2; - if (x < Zero) return -Asin(-x); - - var newX = One - 2 * x * x; - if (Abs(x) > Abs(newX)) - { - var t = Asin(newX); - return Half * (PIdiv2 - t); - } - - decimal y = Zero; - decimal result = x; - decimal cachedResult; - int i = 1; - y += result; - decimal xx = x * x; - do - { - cachedResult = result; - result *= xx * (One - Half / i); - y += result / ((i << 1) + 1); - i++; - } while (cachedResult != result && i < MaxIteration); - return y; - } - - /// - /// Analogy of Math.Atan (safe against overflow for large x) - /// - public static decimal Atan(decimal x) - { - if (x == Zero) return Zero; - if (x == One) return PIdiv4; - if (x == -One) return -PIdiv4; - - if (x > 100000000000000m) return PIdiv2; - if (x < -100000000000000m) return -PIdiv2; - - if (x > One) - { - return PIdiv2 - Atan(One / x); - } - if (x < -One) - { - return -PIdiv2 - Atan(One / x); - } - - return Asin(x / Sqrt(One + x * x)); - } - - /// - /// Analogy of Math.Acos - /// - public static decimal Acos(decimal x) - { - if (x > One || x < -One) - { - throw new ArgumentException("Acos argümanı [-1, 1] aralığında olmalıdır."); - } - if (x == Zero) return PIdiv2; - if (x == One) return Zero; - if (x == -One) return PI; - if (x < Zero) return PI - Acos(-x); - return PIdiv2 - Asin(x); - } - - /// - /// Analogy of Math.Atan2 - /// - public static decimal Atan2(decimal y, decimal x) - { - if (x > Zero) - { - return Atan(y / x); - } - if (x < Zero && y >= Zero) - { - return Atan(y / x) + PI; - } - if (x < Zero && y < Zero) - { - return Atan(y / x) - PI; - } - if (x == Zero && y > Zero) - { - return PIdiv2; - } - if (x == Zero && y < Zero) - { - return -PIdiv2; - } - throw new ArgumentException("Geçersiz Atan2 argümanları (0, 0)."); - } -} diff --git a/tests/ttCalculator.Tests/EigenvalueDecomposition.cs b/tests/ttCalculator.Tests/EigenvalueDecomposition.cs deleted file mode 100644 index 3cf03a8..0000000 --- a/tests/ttCalculator.Tests/EigenvalueDecomposition.cs +++ /dev/null @@ -1,931 +0,0 @@ -using System; -using System.Runtime.InteropServices; -using System.Runtime.Serialization; - -namespace DotNetMatrix -{ - [Serializable] - public class EigenvalueDecomposition : System.Runtime.Serialization.ISerializable - { - private int n; - private bool issymmetric; - private decimal[] d, e; - private decimal[][] V; - private decimal[][] H; - private decimal[] ort; - - private void tred2() - { - for (int j = 0; j < n; j++) - { - d[j] = V[n - 1][j]; - } - - for (int i = n - 1; i > 0; i--) - { - decimal scale = 0.0m; - decimal h = 0.0m; - for (int k = 0; k < i; k++) - { - scale = scale + System.Math.Abs(d[k]); - } - if (scale == 0.0m) - { - e[i] = d[i - 1]; - for (int j = 0; j < i; j++) - { - d[j] = V[i - 1][j]; - V[i][j] = 0.0m; - V[j][i] = 0.0m; - } - } - else - { - for (int k = 0; k < i; k++) - { - d[k] /= scale; - h += d[k] * d[k]; - } - decimal f = d[i - 1]; - decimal g = (decimal)DecimalMath.Sqrt(h); - if (f > 0) - { - g = - g; - } - e[i] = scale * g; - h = h - f * g; - d[i - 1] = f - g; - for (int j = 0; j < i; j++) - { - e[j] = 0.0m; - } - - for (int j = 0; j < i; j++) - { - f = d[j]; - V[j][i] = f; - g = e[j] + V[j][j] * f; - for (int k = j + 1; k <= i - 1; k++) - { - g += V[k][j] * d[k]; - e[k] += V[k][j] * f; - } - e[j] = g; - } - f = 0.0m; - for (int j = 0; j < i; j++) - { - e[j] /= h; - f += e[j] * d[j]; - } - decimal hh = f / (h + h); - for (int j = 0; j < i; j++) - { - e[j] -= hh * d[j]; - } - for (int j = 0; j < i; j++) - { - f = d[j]; - g = e[j]; - for (int k = j; k <= i - 1; k++) - { - V[k][j] -= (f * e[k] + g * d[k]); - } - d[j] = V[i - 1][j]; - V[i][j] = 0.0m; - } - } - d[i] = h; - } - - for (int i = 0; i < n - 1; i++) - { - V[n - 1][i] = V[i][i]; - V[i][i] = 1.0m; - decimal h = d[i + 1]; - if (h != 0.0m) - { - for (int k = 0; k <= i; k++) - { - d[k] = V[k][i + 1] / h; - } - for (int j = 0; j <= i; j++) - { - decimal g = 0.0m; - for (int k = 0; k <= i; k++) - { - g += V[k][i + 1] * V[k][j]; - } - for (int k = 0; k <= i; k++) - { - V[k][j] -= g * d[k]; - } - } - } - for (int k = 0; k <= i; k++) - { - V[k][i + 1] = 0.0m; - } - } - for (int j = 0; j < n; j++) - { - d[j] = V[n - 1][j]; - V[n - 1][j] = 0.0m; - } - V[n - 1][n - 1] = 1.0m; - e[0] = 0.0m; - } - - private void tql2() - { - for (int i = 1; i < n; i++) - { - e[i - 1] = e[i]; - } - e[n - 1] = 0.0m; - - decimal f = 0.0m; - decimal tst1 = 0.0m; - decimal eps = DecimalMath.Pow(2.0m, -64.0m); - for (int l = 0; l < n; l++) - { - tst1 = System.Math.Max(tst1, System.Math.Abs(d[l]) + System.Math.Abs(e[l])); - int m = l; - while (m < n) - { - if (System.Math.Abs(e[m]) <= eps * tst1) - { - break; - } - m++; - } - - if (m > l) - { - int iter = 0; - do - { - iter = iter + 1; - if (iter > 120) break; - decimal g = d[l]; - decimal p = (d[l + 1] - g) / (2.0m * e[l]); - decimal r = Maths.Hypot(p, 1.0m); - if (p < 0) - { - r = - r; - } - d[l] = e[l] / (p + r); - d[l + 1] = e[l] * (p + r); - decimal dl1 = d[l + 1]; - decimal h = g - d[l]; - for (int i = l + 2; i < n; i++) - { - d[i] -= h; - } - f = f + h; - - p = d[m]; - decimal c = 1.0m; - decimal c2 = c; - decimal c3 = c; - decimal el1 = e[l + 1]; - decimal s = 0.0m; - decimal s2 = 0.0m; - for (int i = m - 1; i >= l; i--) - { - c3 = c2; - c2 = c; - s2 = s; - g = c * e[i]; - h = c * p; - r = Maths.Hypot(p, e[i]); - e[i + 1] = s * r; - s = e[i] / r; - c = p / r; - p = c * d[i] - s * g; - d[i + 1] = h + s * (c * g + s * d[i]); - - for (int k = 0; k < n; k++) - { - h = V[k][i + 1]; - V[k][i + 1] = s * V[k][i] + c * h; - V[k][i] = c * V[k][i] - s * h; - } - } - p = (- s) * s2 * c3 * el1 * e[l] / dl1; - e[l] = s * p; - d[l] = c * p; - } - while (System.Math.Abs(e[l]) > eps * tst1); - } - d[l] = d[l] + f; - e[l] = 0.0m; - } - - for (int i = 0; i < n - 1; i++) - { - int k = i; - decimal p = d[i]; - for (int j = i + 1; j < n; j++) - { - if (d[j] < p) - { - k = j; - p = d[j]; - } - } - if (k != i) - { - d[k] = d[i]; - d[i] = p; - for (int j = 0; j < n; j++) - { - p = V[j][i]; - V[j][i] = V[j][k]; - V[j][k] = p; - } - } - } - } - - private void orthes() - { - int low = 0; - int high = n - 1; - - for (int m = low + 1; m <= high - 1; m++) - { - decimal scale = 0.0m; - for (int i = m; i <= high; i++) - { - scale = scale + System.Math.Abs(H[i][m - 1]); - } - if (scale != 0.0m) - { - decimal h = 0.0m; - for (int i = high; i >= m; i--) - { - ort[i] = H[i][m - 1] / scale; - h += ort[i] * ort[i]; - } - decimal g = (decimal)DecimalMath.Sqrt(h); - if (ort[m] > 0) - { - g = - g; - } - h = h - ort[m] * g; - ort[m] = ort[m] - g; - - for (int j = m; j < n; j++) - { - decimal f = 0.0m; - for (int i = high; i >= m; i--) - { - f += ort[i] * H[i][j]; - } - f = f / h; - for (int i = m; i <= high; i++) - { - H[i][j] -= f * ort[i]; - } - } - - for (int i = 0; i <= high; i++) - { - decimal f = 0.0m; - for (int j = high; j >= m; j--) - { - f += ort[j] * H[i][j]; - } - f = f / h; - for (int j = m; j <= high; j++) - { - H[i][j] -= f * ort[j]; - } - } - ort[m] = scale * ort[m]; - H[m][m - 1] = scale * g; - } - } - - for (int i = 0; i < n; i++) - { - for (int j = 0; j < n; j++) - { - V[i][j] = (i == j?1.0m:0.0m); - } - } - - for (int m = high - 1; m >= low + 1; m--) - { - if (H[m][m - 1] != 0.0m) - { - for (int i = m + 1; i <= high; i++) - { - ort[i] = H[i][m - 1]; - } - for (int j = m; j <= high; j++) - { - decimal g = 0.0m; - for (int i = m; i <= high; i++) - { - g += ort[i] * V[i][j]; - } - g = (g / ort[m]) / H[m][m - 1]; - for (int i = m; i <= high; i++) - { - V[i][j] += g * ort[i]; - } - } - } - } - } - - - [NonSerialized()] - private decimal cdivr, cdivi; - - private void cdiv(decimal xr, decimal xi, decimal yr, decimal yi) - { - decimal r, d; - if (System.Math.Abs(yr) > System.Math.Abs(yi)) - { - r = yi / yr; - d = yr + r * yi; - cdivr = (xr + r * xi) / d; - cdivi = (xi - r * xr) / d; - } - else - { - r = yr / yi; - d = yi + r * yr; - cdivr = (r * xr + xi) / d; - cdivi = (r * xi - xr) / d; - } - } - - private void hqr2() - { - int nn = this.n; - int n = nn - 1; - int low = 0; - int high = nn - 1; - decimal eps = (decimal)DecimalMath.Pow(2.0m, - 52.0m); - decimal exshift = 0.0m; - decimal p = 0, q = 0, r = 0, s = 0, z = 0, t, w, x, y; - - decimal norm = 0.0m; - for (int i = 0; i < nn; i++) - { - if (i < low | i > high) - { - d[i] = H[i][i]; - e[i] = 0.0m; - } - for (int j = System.Math.Max(i - 1, 0); j < nn; j++) - { - norm = norm + System.Math.Abs(H[i][j]); - } - } - - int iter = 0; - int totalIter = 0; - while (n >= low && totalIter < 400) - { - totalIter++; - int l = n; - while (l > low) - { - s = System.Math.Abs(H[l - 1][l - 1]) + System.Math.Abs(H[l][l]); - if (s == 0.0m) - { - s = norm; - } - if (System.Math.Abs(H[l][l - 1]) < eps * s) - { - break; - } - l--; - } - - if (l == n) - { - H[n][n] = H[n][n] + exshift; - d[n] = H[n][n]; - e[n] = 0.0m; - n--; - iter = 0; - } - else if (l == n - 1) - { - w = H[n][n - 1] * H[n - 1][n]; - p = (H[n - 1][n - 1] - H[n][n]) / 2.0m; - q = p * p + w; - z = (decimal)DecimalMath.Sqrt(System.Math.Abs(q)); - H[n][n] = H[n][n] + exshift; - H[n - 1][n - 1] = H[n - 1][n - 1] + exshift; - x = H[n][n]; - - if (q >= 0) - { - if (p >= 0) - { - z = p + z; - } - else - { - z = p - z; - } - d[n - 1] = x + z; - d[n] = d[n - 1]; - if (z != 0.0m) - { - d[n] = x - w / z; - } - e[n - 1] = 0.0m; - e[n] = 0.0m; - x = H[n][n - 1]; - s = System.Math.Abs(x) + System.Math.Abs(z); - p = x / s; - q = z / s; - r = (decimal)DecimalMath.Sqrt(p * p + q * q); - p = p / r; - q = q / r; - - for (int j = n - 1; j < nn; j++) - { - z = H[n - 1][j]; - H[n - 1][j] = q * z + p * H[n][j]; - H[n][j] = q * H[n][j] - p * z; - } - - for (int i = 0; i <= n; i++) - { - z = H[i][n - 1]; - H[i][n - 1] = q * z + p * H[i][n]; - H[i][n] = q * H[i][n] - p * z; - } - - for (int i = low; i <= high; i++) - { - z = V[i][n - 1]; - V[i][n - 1] = q * z + p * V[i][n]; - V[i][n] = q * V[i][n] - p * z; - } - - } - else - { - d[n - 1] = x + p; - d[n] = x + p; - e[n - 1] = z; - e[n] = - z; - } - n = n - 2; - iter = 0; - - } - else - { - x = H[n][n]; - y = 0.0m; - w = 0.0m; - if (l < n) - { - y = H[n - 1][n - 1]; - w = H[n][n - 1] * H[n - 1][n]; - } - - if (iter == 10) - { - exshift += x; - for (int i = low; i <= n; i++) - { - H[i][i] -= x; - } - s = System.Math.Abs(H[n][n - 1]) + System.Math.Abs(H[n - 1][n - 2]); - x = y = 0.75m * s; - w = (- 0.4375m) * s * s; - } - - if (iter == 30) - { - s = (y - x) / 2.0m; - s = s * s + w; - if (s > 0) - { - s = (decimal)DecimalMath.Sqrt(s); - if (y < x) - { - s = - s; - } - s = x - w / ((y - x) / 2.0m + s); - for (int i = low; i <= n; i++) - { - H[i][i] -= s; - } - exshift += s; - x = y = w = 0.964m; - } - } - - iter = iter + 1; - - int m = n - 2; - while (m >= l) - { - z = H[m][m]; - r = x - z; - s = y - z; - p = (r * s - w) / H[m + 1][m] + H[m][m + 1]; - q = H[m + 1][m + 1] - z - r - s; - r = H[m + 2][m + 1]; - s = System.Math.Abs(p) + System.Math.Abs(q) + System.Math.Abs(r); - p = p / s; - q = q / s; - r = r / s; - if (m == l) - { - break; - } - if (System.Math.Abs(H[m][m - 1]) * (System.Math.Abs(q) + System.Math.Abs(r)) < eps * (System.Math.Abs(p) * (System.Math.Abs(H[m - 1][m - 1]) + System.Math.Abs(z) + System.Math.Abs(H[m + 1][m + 1])))) - { - break; - } - m--; - } - - for (int i = m + 2; i <= n; i++) - { - H[i][i - 2] = 0.0m; - if (i > m + 2) - { - H[i][i - 3] = 0.0m; - } - } - - for (int k = m; k <= n - 1; k++) - { - bool notlast = (k != n - 1); - if (k != m) - { - p = H[k][k - 1]; - q = H[k + 1][k - 1]; - r = (notlast?H[k + 2][k - 1]:0.0m); - x = System.Math.Abs(p) + System.Math.Abs(q) + System.Math.Abs(r); - if (x != 0.0m) - { - p = p / x; - q = q / x; - r = r / x; - } - } - if (x == 0.0m) - { - break; - } - s = (decimal)DecimalMath.Sqrt(p * p + q * q + r * r); - if (p < 0) - { - s = - s; - } - if (s != 0) - { - if (k != m) - { - H[k][k - 1] = (- s) * x; - } - else if (l != m) - { - H[k][k - 1] = - H[k][k - 1]; - } - p = p + s; - x = p / s; - y = q / s; - z = r / s; - q = q / p; - r = r / p; - - for (int j = k; j < nn; j++) - { - p = H[k][j] + q * H[k + 1][j]; - if (notlast) - { - p = p + r * H[k + 2][j]; - H[k + 2][j] = H[k + 2][j] - p * z; - } - H[k][j] = H[k][j] - p * x; - H[k + 1][j] = H[k + 1][j] - p * y; - } - - for (int i = 0; i <= System.Math.Min(n, k + 3); i++) - { - p = x * H[i][k] + y * H[i][k + 1]; - if (notlast) - { - p = p + z * H[i][k + 2]; - H[i][k + 2] = H[i][k + 2] - p * r; - } - H[i][k] = H[i][k] - p; - H[i][k + 1] = H[i][k + 1] - p * q; - } - - for (int i = low; i <= high; i++) - { - p = x * V[i][k] + y * V[i][k + 1]; - if (notlast) - { - p = p + z * V[i][k + 2]; - V[i][k + 2] = V[i][k + 2] - p * r; - } - V[i][k] = V[i][k] - p; - V[i][k + 1] = V[i][k + 1] - p * q; - } - } - } - } - } - - if (norm == 0.0m) - { - return ; - } - - for (n = nn - 1; n >= 0; n--) - { - p = d[n]; - q = e[n]; - - if (q == 0) - { - int l = n; - H[n][n] = 1.0m; - for (int i = n - 1; i >= 0; i--) - { - w = H[i][i] - p; - r = 0.0m; - for (int j = l; j <= n; j++) - { - r = r + H[i][j] * H[j][n]; - } - if (e[i] < 0.0m) - { - z = w; - s = r; - } - else - { - l = i; - if (e[i] == 0.0m) - { - if (w != 0.0m) - { - H[i][n] = (- r) / w; - } - else - { - H[i][n] = (- r) / (eps * norm); - } - } - else - { - x = H[i][i + 1]; - y = H[i + 1][i]; - q = (d[i] - p) * (d[i] - p) + e[i] * e[i]; - t = (x * s - z * r) / q; - H[i][n] = t; - if (System.Math.Abs(x) > System.Math.Abs(z)) - { - H[i + 1][n] = (- r - w * t) / x; - } - else - { - H[i + 1][n] = (- s - y * t) / z; - } - } - - t = System.Math.Abs(H[i][n]); - if (t > 0 && (t > 1000000000000m || (eps * t) > 1m / t)) - { - for (int j = i; j <= n; j++) - { - H[j][n] = H[j][n] / t; - } - } - } - } - } - else if (q < 0) - { - int l = n - 1; - if (System.Math.Abs(H[n][n - 1]) > System.Math.Abs(H[n - 1][n])) - { - H[n - 1][n - 1] = q / H[n][n - 1]; - H[n - 1][n] = (- (H[n][n] - p)) / H[n][n - 1]; - } - else - { - cdiv(0.0m, - H[n - 1][n], H[n - 1][n - 1] - p, q); - H[n - 1][n - 1] = cdivr; - H[n - 1][n] = cdivi; - } - H[n][n - 1] = 0.0m; - H[n][n] = 1.0m; - for (int i = n - 2; i >= 0; i--) - { - decimal ra, sa, vr, vi; - ra = 0.0m; - sa = 0.0m; - for (int j = l; j <= n; j++) - { - ra = ra + H[i][j] * H[j][n - 1]; - sa = sa + H[i][j] * H[j][n]; - } - w = H[i][i] - p; - - if (e[i] < 0.0m) - { - z = w; - r = ra; - s = sa; - } - else - { - l = i; - if (e[i] == 0) - { - cdiv(- ra, - sa, w, q); - H[i][n - 1] = cdivr; - H[i][n] = cdivi; - } - else - { - x = H[i][i + 1]; - y = H[i + 1][i]; - vr = (d[i] - p) * (d[i] - p) + e[i] * e[i] - q * q; - vi = (d[i] - p) * 2.0m * q; - if (vr == 0.0m & vi == 0.0m) - { - vr = eps * norm * (System.Math.Abs(w) + System.Math.Abs(q) + System.Math.Abs(x) + System.Math.Abs(y) + System.Math.Abs(z)); - } - cdiv(x * r - z * ra + q * sa, x * s - z * sa - q * ra, vr, vi); - H[i][n - 1] = cdivr; - H[i][n] = cdivi; - if (System.Math.Abs(x) > (System.Math.Abs(z) + System.Math.Abs(q))) - { - H[i + 1][n - 1] = (- ra - w * H[i][n - 1] + q * H[i][n]) / x; - H[i + 1][n] = (- sa - w * H[i][n] - q * H[i][n - 1]) / x; - } - else - { - cdiv(- r - y * H[i][n - 1], - s - y * H[i][n], z, q); - H[i + 1][n - 1] = cdivr; - H[i + 1][n] = cdivi; - } - } - - t = System.Math.Max(System.Math.Abs(H[i][n - 1]), System.Math.Abs(H[i][n])); - if (t > 0 && (t > 1000000000000m || (eps * t) > 1m / t)) - { - for (int j = i; j <= n; j++) - { - H[j][n - 1] = H[j][n - 1] / t; - H[j][n] = H[j][n] / t; - } - } - } - } - } - } - - for (int i = 0; i < nn; i++) - { - if (i < low | i > high) - { - for (int j = i; j < nn; j++) - { - V[i][j] = H[i][j]; - } - } - } - - for (int j = nn - 1; j >= low; j--) - { - for (int i = low; i <= high; i++) - { - z = 0.0m; - for (int k = low; k <= System.Math.Min(j, high); k++) - { - z = z + V[i][k] * H[k][j]; - } - V[i][j] = z; - } - } - } - - public EigenvalueDecomposition(GeneralMatrix Arg) - { - decimal[][] A = Arg.Array; - n = Arg.ColumnDimension; - V = new decimal[n][]; - for (int i = 0; i < n; i++) - { - V[i] = new decimal[n]; - } - d = new decimal[n]; - e = new decimal[n]; - - issymmetric = true; - for (int j = 0; (j < n) & issymmetric; j++) - { - for (int i = 0; (i < n) & issymmetric; i++) - { - issymmetric = (A[i][j] == A[j][i]); - } - } - - if (issymmetric) - { - for (int i = 0; i < n; i++) - { - for (int j = 0; j < n; j++) - { - V[i][j] = A[i][j]; - } - } - - tred2(); - tql2(); - } - else - { - H = new decimal[n][]; - for (int i2 = 0; i2 < n; i2++) - { - H[i2] = new decimal[n]; - } - ort = new decimal[n]; - - for (int j = 0; j < n; j++) - { - for (int i = 0; i < n; i++) - { - H[i][j] = A[i][j]; - } - } - - orthes(); - hqr2(); - } - } - - virtual public decimal[] RealEigenvalues - { - get - { - return d; - } - } - virtual public decimal[] ImagEigenvalues - { - get - { - return e; - } - } - virtual public GeneralMatrix D - { - get - { - GeneralMatrix X = new GeneralMatrix(n, n); - decimal[][] D = X.Array; - for (int i = 0; i < n; i++) - { - for (int j = 0; j < n; j++) - { - D[i][j] = 0.0m; - } - D[i][i] = d[i]; - if (e[i] > 0) - { - D[i][i + 1] = e[i]; - } - else if (e[i] < 0) - { - D[i][i - 1] = e[i]; - } - } - return X; - } - } - - public virtual GeneralMatrix GetV() - { - return new GeneralMatrix(V, n, n); - } - - void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) - { - } - } -} diff --git a/tests/ttCalculator.Tests/Function.cs b/tests/ttCalculator.Tests/Function.cs deleted file mode 100644 index 26d7ff8..0000000 --- a/tests/ttCalculator.Tests/Function.cs +++ /dev/null @@ -1,994 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; - -public enum Type { Variable, Value, UnaryOperator, Operator, Function, Result, Bracket, Comma, Error } - -public struct Symbol -{ - public string m_name; - public decimal m_value; - public Type m_type; - public int m_argCount; - public override string ToString() - { - return m_name; - } -} - -public delegate Symbol EvaluateFunctionDelegate(string name, params Symbol[] args); - -public class Function -{ - private static readonly HashSet KnownFunctions = new HashSet(StringComparer.OrdinalIgnoreCase) - { - "sin", "cos", "tan", "cot", "cosh", "sinh", "tanh", - "log", "ln", "logn", "sqrt", "cbrt", "abs", - "acos", "asin", "atan", "atan2", "exp", - "max", "min", "floor", "ceil", "round", "sign" - }; - - public static bool UseRadians { get; set; } = true; - - public decimal Result => m_result; - public ArrayList Equation => (ArrayList)m_equation.Clone(); - public ArrayList Postfix => (ArrayList)m_postfix.Clone(); - - public EvaluateFunctionDelegate DefaultFunctionEvaluation - { - set => m_defaultFunctionEvaluation = value; - } - - public bool Error => m_bError; - public string ErrorDescription => m_sErrorDescription; - - public ArrayList Variables - { - get - { - ArrayList var = new ArrayList(); - foreach (Symbol sym in m_equation) - { - if ((sym.m_type == Type.Variable) && (!var.Contains(sym))) - var.Add(sym); - } - return var; - } - set - { - foreach (Symbol sym in value) - { - for (int i = 0; i < m_postfix.Count; i++) - { - if ((sym.m_name == ((Symbol)m_postfix[i]).m_name) && (((Symbol)m_postfix[i]).m_type == Type.Variable)) - { - Symbol sym1 = (Symbol)m_postfix[i]; - sym1.m_value = sym.m_value; - m_postfix[i] = sym1; - } - } - } - } - } - - public void SetVariable(string name, decimal value) - { - for (int i = 0; i < m_postfix.Count; i++) - { - Symbol s = (Symbol)m_postfix[i]; - if (s.m_type == Type.Variable && string.Equals(s.m_name, name, StringComparison.OrdinalIgnoreCase)) - { - s.m_value = value; - m_postfix[i] = s; - } - } - } - - public void SetVariables(Dictionary values) - { - for (int i = 0; i < m_postfix.Count; i++) - { - Symbol s = (Symbol)m_postfix[i]; - if (s.m_type == Type.Variable && values.TryGetValue(s.m_name, out decimal val)) - { - s.m_value = val; - m_postfix[i] = s; - } - } - } - - public Function() - { - } - - private void AddSymbolWithImplicitMultiplication(Symbol sym) - { - if (m_equation.Count > 0) - { - Symbol prev = (Symbol)m_equation[m_equation.Count - 1]; - bool prevIsOperandOrClose = prev.m_type == Type.Value || - prev.m_type == Type.Variable || - prev.m_name == ")" || prev.m_name == "]" || prev.m_name == "}"; - - bool currIsOperandOrOpen = sym.m_type == Type.Value || - sym.m_type == Type.Variable || - sym.m_type == Type.Function || - sym.m_name == "(" || sym.m_name == "[" || sym.m_name == "{"; - - if (prevIsOperandOrClose && currIsOperandOrOpen) - { - Symbol mulSym = new Symbol - { - m_name = "*", - m_value = 0, - m_type = Type.Operator - }; - m_equation.Add(mulSym); - } - } - m_equation.Add(sym); - } - - public void Parse(string equation) - { - int state = 1; - string temp = ""; - Symbol ctSymbol = new Symbol(); - - m_bError = false; - m_sErrorDescription = "None"; - - m_equation.Clear(); - m_postfix.Clear(); - - if (string.IsNullOrWhiteSpace(equation)) - { - m_bError = true; - m_sErrorDescription = "Denklem boş olamaz."; - return; - } - - // We process whitespace as delimiter without deleting it globally - for (int i = 0; i < equation.Length; i++) - { - char ch = equation[i]; - switch (state) - { - case 1: // Neutral - if (char.IsWhiteSpace(ch)) - { - continue; - } - if (char.IsDigit(ch) || ch == '.') - { - state = 2; - temp += ch; - } - else if (char.IsLetter(ch)) - { - state = 3; - temp += ch; - } - else - { - ctSymbol = ClassifyNonAlphanumeric(ch.ToString()); - AddSymbolWithImplicitMultiplication(ctSymbol); - } - break; - - case 2: // Reading Number - if (char.IsDigit(ch) || ch == '.') - { - temp += ch; - } - else if (char.IsWhiteSpace(ch)) - { - if (!EmitNumberSymbol(temp)) return; - temp = ""; - state = 1; - } - else - { - if (!EmitNumberSymbol(temp)) return; - temp = ""; - - if (char.IsLetter(ch)) - { - state = 3; - temp += ch; - } - else - { - state = 1; - ctSymbol = ClassifyNonAlphanumeric(ch.ToString()); - AddSymbolWithImplicitMultiplication(ctSymbol); - } - } - break; - - case 3: // Reading Identifier - if (char.IsLetterOrDigit(ch)) - { - temp += ch; - } - else if (char.IsWhiteSpace(ch)) - { - // Lookahead to see if next non-whitespace is '(' - bool nextIsOpen = false; - for (int k = i + 1; k < equation.Length; k++) - { - if (!char.IsWhiteSpace(equation[k])) - { - nextIsOpen = (equation[k] == '(' || equation[k] == '[' || equation[k] == '{'); - break; - } - } - EmitIdentifierSymbol(temp, nextIsOpen); - temp = ""; - state = 1; - } - else - { - state = 1; - EmitIdentifierSymbol(temp, ch == '(' || ch == '[' || ch == '{'); - temp = ""; - - ctSymbol = ClassifyNonAlphanumeric(ch.ToString()); - AddSymbolWithImplicitMultiplication(ctSymbol); - } - break; - } - } - - if (temp != "") - { - if (state == 2) - { - if (!EmitNumberSymbol(temp)) return; - } - else - { - EmitIdentifierSymbol(temp, false); - } - } - } - - private bool EmitNumberSymbol(string temp) - { - if (!decimal.TryParse(temp, NumberStyles.Any, CultureInfo.InvariantCulture, out decimal val)) - { - m_bError = true; - m_sErrorDescription = "Geçersiz sayı formatı: " + temp; - return false; - } - - Symbol sym = new Symbol - { - m_name = temp, - m_value = val, - m_type = Type.Value - }; - AddSymbolWithImplicitMultiplication(sym); - return true; - } - - private void EmitIdentifierSymbol(string temp, bool isNextOpenParen) - { - Symbol sym = new Symbol - { - m_name = temp, - m_value = 0 - }; - - string lower = temp.ToLowerInvariant(); - if (lower == "pi") - { - sym.m_value = DecimalMath.PI; - sym.m_type = Type.Value; - } - else if (lower == "e") - { - sym.m_value = DecimalMath.E; - sym.m_type = Type.Value; - } - else if (isNextOpenParen) - { - if (temp.Length == 1 && (temp == "x" || temp == "y" || temp == "z" || temp == "t" || temp == "u" || temp == "v")) - { - sym.m_type = Type.Variable; - } - else - { - sym.m_type = Type.Function; - } - } - else - { - sym.m_type = Type.Variable; - } - AddSymbolWithImplicitMultiplication(sym); - } - - private Symbol ClassifyNonAlphanumeric(string token) - { - Symbol ctSymbol = new Symbol - { - m_name = token, - m_value = 0 - }; - - switch (token) - { - case ",": - case ";": - ctSymbol.m_type = Type.Comma; - break; - case "(": - case ")": - case "[": - case "]": - case "{": - case "}": - ctSymbol.m_type = Type.Bracket; - break; - default: - if (m_equation.Count == 0) - { - ctSymbol.m_type = Type.UnaryOperator; - } - else - { - Symbol prev = (Symbol)m_equation[m_equation.Count - 1]; - if (prev.m_type == Type.Value || prev.m_type == Type.Variable || - prev.m_name == ")" || prev.m_name == "]" || prev.m_name == "}") - { - ctSymbol.m_type = Type.Operator; - } - else - { - ctSymbol.m_type = Type.UnaryOperator; - } - } - break; - } - return ctSymbol; - } - - public void Infix2Postfix() - { - m_postfix.Clear(); - Symbol tpSym; - Stack tpStack = new Stack(); - Stack fnArgCounts = new Stack(); - - foreach (Symbol sym in m_equation) - { - if ((sym.m_type == Type.Value) || (sym.m_type == Type.Variable)) - m_postfix.Add(sym); - else if (sym.m_type == Type.Function) - { - tpStack.Push(sym); - fnArgCounts.Push(1); - } - else if ((sym.m_name == "(") || (sym.m_name == "[") || (sym.m_name == "{")) - tpStack.Push(sym); - else if (sym.m_type == Type.Comma) - { - while (tpStack.Count > 0) - { - tpSym = (Symbol)tpStack.Peek(); - if (tpSym.m_name == "(" || tpSym.m_name == "[" || tpSym.m_name == "{") - break; - m_postfix.Add(tpStack.Pop()); - } - if (fnArgCounts.Count > 0) - { - int c = fnArgCounts.Pop(); - fnArgCounts.Push(c + 1); - } - } - else if ((sym.m_name == ")") || (sym.m_name == "]") || (sym.m_name == "}")) - { - if (tpStack.Count > 0) - { - tpSym = (Symbol)tpStack.Pop(); - while ((tpSym.m_name != "(") && (tpSym.m_name != "[") && (tpSym.m_name != "{")) - { - m_postfix.Add(tpSym); - if (tpStack.Count == 0) break; - tpSym = (Symbol)tpStack.Pop(); - } - - if (tpStack.Count > 0 && ((Symbol)tpStack.Peek()).m_type == Type.Function) - { - Symbol fn = (Symbol)tpStack.Pop(); - fn.m_argCount = fnArgCounts.Count > 0 ? fnArgCounts.Pop() : 1; - m_postfix.Add(fn); - } - } - } - else if (sym.m_type == Type.UnaryOperator) - { - // Unary operators (like unary - or +) modify the operand to their right. - // They should never pop binary operators (^, *, /, +, -) from the stack. - tpStack.Push(sym); - } - else if (sym.m_name == "^") - { - // Right-associative operator ^ - while (tpStack.Count > 0) - { - tpSym = (Symbol)tpStack.Peek(); - if ((tpSym.m_type == Type.Operator || tpSym.m_type == Type.Function) && - Precedence(tpSym) > Precedence(sym)) - { - m_postfix.Add(tpStack.Pop()); - } - else - { - break; - } - } - tpStack.Push(sym); - } - else - { - while (tpStack.Count > 0) - { - tpSym = (Symbol)tpStack.Peek(); - if (((tpSym.m_type == Type.UnaryOperator) || (tpSym.m_type == Type.Operator) || (tpSym.m_type == Type.Function)) && - (Precedence(tpSym) >= Precedence(sym))) - { - m_postfix.Add(tpStack.Pop()); - } - else - { - break; - } - } - tpStack.Push(sym); - } - } - while (tpStack.Count > 0) - { - tpSym = (Symbol)tpStack.Pop(); - if (tpSym.m_type == Type.Function && tpSym.m_argCount == 0) - { - tpSym.m_argCount = fnArgCounts.Count > 0 ? fnArgCounts.Pop() : 1; - } - m_postfix.Add(tpSym); - } - } - - public void EvaluatePostfix() - { - Symbol tpSym1, tpSym2, tpResult; - Stack tpStack = new Stack(); - m_bError = false; - foreach (Symbol sym in m_postfix) - { - if ((sym.m_type == Type.Value) || (sym.m_type == Type.Variable) || (sym.m_type == Type.Result)) - tpStack.Push(sym); - else if (sym.m_type == Type.UnaryOperator) - { - if (tpStack.Count < 1) - { - m_bError = true; - m_sErrorDescription = "Sözdizimi hatası (eksik operand)."; - return; - } - tpSym1 = (Symbol)tpStack.Pop(); - tpResult = Evaluate(sym, tpSym1); - if (tpResult.m_type == Type.Error) - { - m_bError = true; - m_sErrorDescription = tpResult.m_name; - return; - } - tpStack.Push(tpResult); - } - else if (sym.m_type == Type.Operator) - { - if (tpStack.Count < 2) - { - m_bError = true; - m_sErrorDescription = "Sözdizimi hatası (eksik operand)."; - return; - } - tpSym1 = (Symbol)tpStack.Pop(); - tpSym2 = (Symbol)tpStack.Pop(); - tpResult = Evaluate(tpSym2, sym, tpSym1); - if (tpResult.m_type == Type.Error) - { - m_bError = true; - m_sErrorDescription = tpResult.m_name; - return; - } - tpStack.Push(tpResult); - } - else if (sym.m_type == Type.Function) - { - int count = sym.m_argCount > 0 ? sym.m_argCount : 1; - if (tpStack.Count < count) - { - m_bError = true; - m_sErrorDescription = $"Fonksiyon '{sym.m_name}' için argüman eksik."; - return; - } - - Symbol[] fnParam = new Symbol[count]; - for (int i = count - 1; i >= 0; i--) - { - fnParam[i] = (Symbol)tpStack.Pop(); - } - - tpResult = EvaluateFunction(sym.m_name, fnParam); - if (tpResult.m_type == Type.Error) - { - m_bError = true; - m_sErrorDescription = tpResult.m_name; - return; - } - tpStack.Push(tpResult); - } - } - if (tpStack.Count == 1) - { - tpResult = (Symbol)tpStack.Pop(); - m_result = tpResult.m_value; - } - else if (tpStack.Count > 1) - { - m_bError = true; - m_sErrorDescription = "İfade tam çözümlenemedi (fazla terim)."; - } - } - - protected int Precedence(Symbol sym) - { - switch (sym.m_type) - { - case Type.Bracket: - return 7; - case Type.Function: - return 6; - case Type.UnaryOperator: - return 3; - case Type.Comma: - return 0; - } - switch (sym.m_name) - { - case "^": - return 5; - case "/": - case "*": - case "%": - return 2; - case "+": - case "-": - return 1; - } - return -1; - } - - protected Symbol Evaluate(Symbol opr, Symbol sym1) - { - Symbol result = default; - result.m_name = opr.m_name + sym1.m_name; - result.m_type = Type.Result; - result.m_value = 0; - switch (opr.m_name) - { - case "+": - result.m_value = sym1.m_value; - break; - case "-": - result.m_value = -1 * sym1.m_value; - break; - default: - result.m_type = Type.Error; - result.m_name = "Tanımsız tekli operatör: " + opr.m_name; - break; - } - return result; - } - - protected Symbol Evaluate(Symbol sym1, Symbol opr, Symbol sym2) - { - Symbol result = default; - result.m_name = sym1.m_name + opr.m_name + sym2.m_name; - result.m_type = Type.Result; - result.m_value = 0; - try - { - switch (opr.m_name) - { - case "^": - result.m_value = DecimalMath.Pow(sym1.m_value, sym2.m_value); - break; - case "/": - if (sym2.m_value != 0) - result.m_value = sym1.m_value / sym2.m_value; - else - { - result.m_name = "Sıfıra bölme hatası (Divide by Zero)."; - result.m_type = Type.Error; - } - break; - case "*": - result.m_value = sym1.m_value * sym2.m_value; - break; - case "%": - if (sym2.m_value != 0) - result.m_value = sym1.m_value % sym2.m_value; - else - { - result.m_name = "Sıfıra göre mod alınamaz."; - result.m_type = Type.Error; - } - break; - case "+": - result.m_value = sym1.m_value + sym2.m_value; - break; - case "-": - result.m_value = sym1.m_value - sym2.m_value; - break; - default: - result.m_type = Type.Error; - result.m_name = "Tanımsız operatör: " + opr.m_name; - break; - } - } - catch (Exception ex) - { - result.m_type = Type.Error; - result.m_name = ex.Message; - } - return result; - } - - protected Symbol EvaluateFunction(string name, params Symbol[] args) - { - Symbol result = default; - result.m_name = ""; - result.m_type = Type.Result; - result.m_value = 0; - - string lowerName = name.ToLowerInvariant(); - decimal angleFactor = UseRadians ? 1.0m : (DecimalMath.PI / 180.0m); - decimal invAngleFactor = UseRadians ? 1.0m : (180.0m / DecimalMath.PI); - - try - { - switch (lowerName) - { - case "cos": - if (args.Length == 1) - { - decimal v = ((Symbol)args[0]).m_value; - result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; - result.m_value = DecimalMath.Cos(v * angleFactor); - } - else - { - result.m_name = "Geçersiz parametre sayısı: " + name; - result.m_type = Type.Error; - } - break; - case "sin": - if (args.Length == 1) - { - decimal v = ((Symbol)args[0]).m_value; - result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; - result.m_value = DecimalMath.Sin(v * angleFactor); - } - else - { - result.m_name = "Geçersiz parametre sayısı: " + name; - result.m_type = Type.Error; - } - break; - case "tan": - if (args.Length == 1) - { - decimal v = ((Symbol)args[0]).m_value; - result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; - result.m_value = DecimalMath.Tan(v * angleFactor); - } - else - { - result.m_name = "Geçersiz parametre sayısı: " + name; - result.m_type = Type.Error; - } - break; - case "cot": - if (args.Length == 1) - { - decimal v = ((Symbol)args[0]).m_value; - result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; - decimal sinVal = DecimalMath.Sin(v * angleFactor); - if (DecimalMath.Abs(sinVal) <= 1e-25m) - { - result.m_name = "Cot(x) bu noktada tanımsızdır (sin(x) = 0)."; - result.m_type = Type.Error; - } - else - { - result.m_value = DecimalMath.Cos(v * angleFactor) / sinVal; - } - } - else - { - result.m_name = "Geçersiz parametre sayısı: " + name; - result.m_type = Type.Error; - } - break; - case "cosh": - if (args.Length == 1) - { - decimal v = ((Symbol)args[0]).m_value; - result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; - result.m_value = DecimalMath.Cosh(v); - } - else - { - result.m_name = "Geçersiz parametre sayısı: " + name; - result.m_type = Type.Error; - } - break; - case "sinh": - if (args.Length == 1) - { - decimal v = ((Symbol)args[0]).m_value; - result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; - result.m_value = DecimalMath.Sinh(v); - } - else - { - result.m_name = "Geçersiz parametre sayısı: " + name; - result.m_type = Type.Error; - } - break; - case "tanh": - if (args.Length == 1) - { - decimal v = ((Symbol)args[0]).m_value; - result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; - result.m_value = DecimalMath.Tanh(v); - } - else - { - result.m_name = "Geçersiz parametre sayısı: " + name; - result.m_type = Type.Error; - } - break; - case "log": - if (args.Length == 1) - { - decimal v = ((Symbol)args[0]).m_value; - result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; - result.m_value = DecimalMath.Log10(v); - } - else if (args.Length == 2) - { - decimal v = ((Symbol)args[0]).m_value; - decimal b = ((Symbol)args[1]).m_value; - result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + "," + b.ToString(CultureInfo.InvariantCulture) + ")"; - result.m_value = DecimalMath.Log(v) / DecimalMath.Log(b); - } - else - { - result.m_name = "Geçersiz parametre sayısı: " + name; - result.m_type = Type.Error; - } - break; - case "ln": - if (args.Length == 1) - { - decimal v = ((Symbol)args[0]).m_value; - result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; - result.m_value = DecimalMath.Log(v); - } - else - { - result.m_name = "Geçersiz parametre sayısı: " + name; - result.m_type = Type.Error; - } - break; - case "logn": - if (args.Length == 2) - { - decimal v = ((Symbol)args[0]).m_value; - decimal b = ((Symbol)args[1]).m_value; - result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + "," + b.ToString(CultureInfo.InvariantCulture) + ")"; - result.m_value = DecimalMath.Log(v) / DecimalMath.Log(b); - } - else - { - result.m_name = "Geçersiz parametre sayısı: " + name; - result.m_type = Type.Error; - } - break; - case "sqrt": - if (args.Length == 1) - { - decimal v = ((Symbol)args[0]).m_value; - result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; - result.m_value = DecimalMath.Sqrt(v); - } - else - { - result.m_name = "Geçersiz parametre sayısı: " + name; - result.m_type = Type.Error; - } - break; - case "cbrt": - if (args.Length == 1) - { - decimal v = ((Symbol)args[0]).m_value; - result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; - result.m_value = v < 0 ? -DecimalMath.Pow(-v, 1m / 3m) : DecimalMath.Pow(v, 1m / 3m); - } - else - { - result.m_name = "Geçersiz parametre sayısı: " + name; - result.m_type = Type.Error; - } - break; - case "abs": - if (args.Length == 1) - { - decimal v = ((Symbol)args[0]).m_value; - result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; - result.m_value = DecimalMath.Abs(v); - } - else - { - result.m_name = "Geçersiz parametre sayısı: " + name; - result.m_type = Type.Error; - } - break; - case "acos": - if (args.Length == 1) - { - decimal v = ((Symbol)args[0]).m_value; - result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; - result.m_value = DecimalMath.Acos(v) * invAngleFactor; - } - else - { - result.m_name = "Geçersiz parametre sayısı: " + name; - result.m_type = Type.Error; - } - break; - case "asin": - if (args.Length == 1) - { - decimal v = ((Symbol)args[0]).m_value; - result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; - result.m_value = DecimalMath.Asin(v) * invAngleFactor; - } - else - { - result.m_name = "Geçersiz parametre sayısı: " + name; - result.m_type = Type.Error; - } - break; - case "atan": - if (args.Length == 1) - { - decimal v = ((Symbol)args[0]).m_value; - result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; - result.m_value = DecimalMath.Atan(v) * invAngleFactor; - } - else - { - result.m_name = "Geçersiz parametre sayısı: " + name; - result.m_type = Type.Error; - } - break; - case "atan2": - if (args.Length == 2) - { - decimal y = ((Symbol)args[0]).m_value; - decimal x = ((Symbol)args[1]).m_value; - result.m_name = name + "(" + y.ToString(CultureInfo.InvariantCulture) + "," + x.ToString(CultureInfo.InvariantCulture) + ")"; - result.m_value = DecimalMath.Atan2(y, x) * invAngleFactor; - } - else - { - result.m_name = "Geçersiz parametre sayısı: atan2(y, x)"; - result.m_type = Type.Error; - } - break; - case "exp": - if (args.Length == 1) - { - decimal v = ((Symbol)args[0]).m_value; - result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; - result.m_value = DecimalMath.Exp(v); - } - else - { - result.m_name = "Geçersiz parametre sayısı: " + name; - result.m_type = Type.Error; - } - break; - case "max": - if (args.Length == 2) - { - decimal a = ((Symbol)args[0]).m_value; - decimal b = ((Symbol)args[1]).m_value; - result.m_value = Math.Max(a, b); - } - else - { - result.m_name = "Geçersiz parametre sayısı: max(a, b)"; - result.m_type = Type.Error; - } - break; - case "min": - if (args.Length == 2) - { - decimal a = ((Symbol)args[0]).m_value; - decimal b = ((Symbol)args[1]).m_value; - result.m_value = Math.Min(a, b); - } - else - { - result.m_name = "Geçersiz parametre sayısı: min(a, b)"; - result.m_type = Type.Error; - } - break; - case "floor": - if (args.Length == 1) - { - result.m_value = decimal.Floor(((Symbol)args[0]).m_value); - } - break; - case "ceil": - if (args.Length == 1) - { - result.m_value = decimal.Ceiling(((Symbol)args[0]).m_value); - } - break; - case "round": - if (args.Length == 1) - { - result.m_value = decimal.Round(((Symbol)args[0]).m_value); - } - break; - case "sign": - if (args.Length == 1) - { - result.m_value = DecimalMath.Sign(((Symbol)args[0]).m_value); - } - break; - default: - if (m_defaultFunctionEvaluation != null) - result = m_defaultFunctionEvaluation(name, args); - else - { - result.m_name = "Fonksiyon bulunamadı: " + name; - result.m_type = Type.Error; - } - break; - } - } - catch (Exception ex) - { - result.m_name = ex.Message; - result.m_type = Type.Error; - } - return result; - } - - protected bool m_bError = false; - protected string m_sErrorDescription = "None"; - public decimal m_result = 0; - public ArrayList m_equation = new ArrayList(); - public ArrayList m_postfix = new ArrayList(); - protected EvaluateFunctionDelegate m_defaultFunctionEvaluation; -} diff --git a/tests/ttCalculator.Tests/GeneralMatrix.cs b/tests/ttCalculator.Tests/GeneralMatrix.cs deleted file mode 100644 index a026b32..0000000 --- a/tests/ttCalculator.Tests/GeneralMatrix.cs +++ /dev/null @@ -1,767 +0,0 @@ -using System; -using System.Runtime.Serialization; - -namespace DotNetMatrix -{ - internal class Maths - { - public static decimal Hypot(decimal a, decimal b) - { - decimal r; - if (Math.Abs(a) > Math.Abs(b)) - { - r = b/a; - r = Math.Abs(a) * (decimal)DecimalMath.Sqrt(1 + r * r); - } - else if (b != 0) - { - r = a/b; - r = Math.Abs(b) * (decimal)DecimalMath.Sqrt(1 + r * r); - } - else - { - r = 0.0m; - } - return r; - } - } - - [Serializable] - public class GeneralMatrix : System.ICloneable, System.Runtime.Serialization.ISerializable, System.IDisposable - { - private decimal[][] A; - private int m, n; - - public GeneralMatrix(int m, int n) - { - this.m = m; - this.n = n; - A = new decimal[m][]; - for (int i = 0; i < m; i++) - { - A[i] = new decimal[n]; - } - } - - public GeneralMatrix(int m, int n, decimal s) - { - this.m = m; - this.n = n; - A = new decimal[m][]; - for (int i = 0; i < m; i++) - { - A[i] = new decimal[n]; - for (int j = 0; j < n; j++) - { - A[i][j] = s; - } - } - } - - public GeneralMatrix(decimal[][] A) - { - m = A.Length; - n = A[0].Length; - for (int i = 0; i < m; i++) - { - if (A[i].Length != n) - { - throw new System.ArgumentException("All rows must have the same length."); - } - } - this.A = A; - } - - public GeneralMatrix(decimal[][] A, int m, int n) - { - this.A = A; - this.m = m; - this.n = n; - } - - public GeneralMatrix(decimal[] vals, int m) - { - this.m = m; - n = (m != 0?vals.Length / m:0); - if (m * n != vals.Length) - { - throw new System.ArgumentException("Array length must be a multiple of m."); - } - A = new decimal[m][]; - for (int i = 0; i < m; i++) - { - A[i] = new decimal[n]; - for (int j = 0; j < n; j++) - { - A[i][j] = vals[i + j * m]; - } - } - } - - public virtual decimal[][] Array - { - get - { - return A; - } - } - - public virtual decimal[][] ArrayCopy - { - get - { - decimal[][] C = new decimal[m][]; - for (int i = 0; i < m; i++) - { - C[i] = new decimal[n]; - for (int j = 0; j < n; j++) - { - C[i][j] = A[i][j]; - } - } - return C; - } - } - - public virtual decimal[] ColumnPackedCopy - { - get - { - decimal[] vals = new decimal[m * n]; - for (int i = 0; i < m; i++) - { - for (int j = 0; j < n; j++) - { - vals[i + j * m] = A[i][j]; - } - } - return vals; - } - } - - public virtual decimal[] RowPackedCopy - { - get - { - decimal[] vals = new decimal[m * n]; - for (int i = 0; i < m; i++) - { - for (int j = 0; j < n; j++) - { - vals[i * n + j] = A[i][j]; - } - } - return vals; - } - } - - public virtual int RowDimension - { - get - { - return m; - } - } - - public virtual int ColumnDimension - { - get - { - return n; - } - } - - public static GeneralMatrix ConstructWithCopy(decimal[][] A) - { - int m = A.Length; - int n = A[0].Length; - GeneralMatrix X = new GeneralMatrix(m, n); - decimal[][] C = X.Array; - for (int i = 0; i < m; i++) - { - if (A[i].Length != n) - { - throw new System.ArgumentException("All rows must have the same length."); - } - for (int j = 0; j < n; j++) - { - C[i][j] = A[i][j]; - } - } - return X; - } - - public virtual GeneralMatrix Copy() - { - GeneralMatrix X = new GeneralMatrix(m, n); - decimal[][] C = X.Array; - for (int i = 0; i < m; i++) - { - for (int j = 0; j < n; j++) - { - C[i][j] = A[i][j]; - } - } - return X; - } - - public virtual decimal GetElement(int i, int j) - { - return A[i][j]; - } - - public virtual GeneralMatrix GetMatrix(int i0, int i1, int j0, int j1) - { - GeneralMatrix X = new GeneralMatrix(i1 - i0 + 1, j1 - j0 + 1); - decimal[][] B = X.Array; - try - { - for (int i = i0; i <= i1; i++) - { - for (int j = j0; j <= j1; j++) - { - B[i - i0][j - j0] = A[i][j]; - } - } - } - catch (System.IndexOutOfRangeException e) - { - throw new System.IndexOutOfRangeException("Submatrix indices", e); - } - return X; - } - - public virtual GeneralMatrix GetMatrix(int[] r, int[] c) - { - GeneralMatrix X = new GeneralMatrix(r.Length, c.Length); - decimal[][] B = X.Array; - try - { - for (int i = 0; i < r.Length; i++) - { - for (int j = 0; j < c.Length; j++) - { - B[i][j] = A[r[i]][c[j]]; - } - } - } - catch (System.IndexOutOfRangeException e) - { - throw new System.IndexOutOfRangeException("Submatrix indices", e); - } - return X; - } - - public virtual GeneralMatrix GetMatrix(int i0, int i1, int[] c) - { - GeneralMatrix X = new GeneralMatrix(i1 - i0 + 1, c.Length); - decimal[][] B = X.Array; - try - { - for (int i = i0; i <= i1; i++) - { - for (int j = 0; j < c.Length; j++) - { - B[i - i0][j] = A[i][c[j]]; - } - } - } - catch (System.IndexOutOfRangeException e) - { - throw new System.IndexOutOfRangeException("Submatrix indices", e); - } - return X; - } - - public virtual GeneralMatrix GetMatrix(int[] r, int j0, int j1) - { - GeneralMatrix X = new GeneralMatrix(r.Length, j1 - j0 + 1); - decimal[][] B = X.Array; - try - { - for (int i = 0; i < r.Length; i++) - { - for (int j = j0; j <= j1; j++) - { - B[i][j - j0] = A[r[i]][j]; - } - } - } - catch (System.IndexOutOfRangeException e) - { - throw new System.IndexOutOfRangeException("Submatrix indices", e); - } - return X; - } - - public virtual void SetElement(int i, int j, decimal s) - { - A[i][j] = s; - } - - public virtual void SetMatrix(int i0, int i1, int j0, int j1, GeneralMatrix X) - { - try - { - for (int i = i0; i <= i1; i++) - { - for (int j = j0; j <= j1; j++) - { - A[i][j] = X.GetElement(i - i0, j - j0); - } - } - } - catch (System.IndexOutOfRangeException e) - { - throw new System.IndexOutOfRangeException("Submatrix indices", e); - } - } - - public virtual void SetMatrix(int[] r, int[] c, GeneralMatrix X) - { - try - { - for (int i = 0; i < r.Length; i++) - { - for (int j = 0; j < c.Length; j++) - { - A[r[i]][c[j]] = X.GetElement(i, j); - } - } - } - catch (System.IndexOutOfRangeException e) - { - throw new System.IndexOutOfRangeException("Submatrix indices", e); - } - } - - public virtual void SetMatrix(int[] r, int j0, int j1, GeneralMatrix X) - { - try - { - for (int i = 0; i < r.Length; i++) - { - for (int j = j0; j <= j1; j++) - { - A[r[i]][j] = X.GetElement(i, j - j0); - } - } - } - catch (System.IndexOutOfRangeException e) - { - throw new System.IndexOutOfRangeException("Submatrix indices", e); - } - } - - public virtual void SetMatrix(int i0, int i1, int[] c, GeneralMatrix X) - { - try - { - for (int i = i0; i <= i1; i++) - { - for (int j = 0; j < c.Length; j++) - { - A[i][c[j]] = X.GetElement(i - i0, j); - } - } - } - catch (System.IndexOutOfRangeException e) - { - throw new System.IndexOutOfRangeException("Submatrix indices", e); - } - } - - public virtual GeneralMatrix Transpose() - { - GeneralMatrix X = new GeneralMatrix(n, m); - decimal[][] C = X.Array; - for (int i = 0; i < m; i++) - { - for (int j = 0; j < n; j++) - { - C[j][i] = A[i][j]; - } - } - return X; - } - - public virtual decimal Norm1() - { - decimal f = 0; - for (int j = 0; j < n; j++) - { - decimal s = 0; - for (int i = 0; i < m; i++) - { - s += System.Math.Abs(A[i][j]); - } - f = System.Math.Max(f, s); - } - return f; - } - - public virtual decimal NormInf() - { - decimal f = 0; - for (int i = 0; i < m; i++) - { - decimal s = 0; - for (int j = 0; j < n; j++) - { - s += System.Math.Abs(A[i][j]); - } - f = System.Math.Max(f, s); - } - return f; - } - - public virtual decimal NormF() - { - decimal f = 0; - for (int i = 0; i < m; i++) - { - for (int j = 0; j < n; j++) - { - f = Maths.Hypot(f, A[i][j]); - } - } - return f; - } - - public virtual GeneralMatrix UnaryMinus() - { - GeneralMatrix X = new GeneralMatrix(m, n); - decimal[][] C = X.Array; - for (int i = 0; i < m; i++) - { - for (int j = 0; j < n; j++) - { - C[i][j] = - A[i][j]; - } - } - return X; - } - - public virtual GeneralMatrix Add(GeneralMatrix B) - { - CheckMatrixDimensions(B); - GeneralMatrix X = new GeneralMatrix(m, n); - decimal[][] C = X.Array; - for (int i = 0; i < m; i++) - { - for (int j = 0; j < n; j++) - { - C[i][j] = A[i][j] + B.A[i][j]; - } - } - return X; - } - - public virtual GeneralMatrix AddEquals(GeneralMatrix B) - { - CheckMatrixDimensions(B); - for (int i = 0; i < m; i++) - { - for (int j = 0; j < n; j++) - { - A[i][j] = A[i][j] + B.A[i][j]; - } - } - return this; - } - - public virtual GeneralMatrix Subtract(GeneralMatrix B) - { - CheckMatrixDimensions(B); - GeneralMatrix X = new GeneralMatrix(m, n); - decimal[][] C = X.Array; - for (int i = 0; i < m; i++) - { - for (int j = 0; j < n; j++) - { - C[i][j] = A[i][j] - B.A[i][j]; - } - } - return X; - } - - public virtual GeneralMatrix SubtractEquals(GeneralMatrix B) - { - CheckMatrixDimensions(B); - for (int i = 0; i < m; i++) - { - for (int j = 0; j < n; j++) - { - A[i][j] = A[i][j] - B.A[i][j]; - } - } - return this; - } - - public virtual GeneralMatrix ArrayMultiply(GeneralMatrix B) - { - CheckMatrixDimensions(B); - GeneralMatrix X = new GeneralMatrix(m, n); - decimal[][] C = X.Array; - for (int i = 0; i < m; i++) - { - for (int j = 0; j < n; j++) - { - C[i][j] = A[i][j] * B.A[i][j]; - } - } - return X; - } - - public virtual GeneralMatrix ArrayMultiplyEquals(GeneralMatrix B) - { - CheckMatrixDimensions(B); - for (int i = 0; i < m; i++) - { - for (int j = 0; j < n; j++) - { - A[i][j] = A[i][j] * B.A[i][j]; - } - } - return this; - } - - public virtual GeneralMatrix ArrayRightDivide(GeneralMatrix B) - { - CheckMatrixDimensions(B); - GeneralMatrix X = new GeneralMatrix(m, n); - decimal[][] C = X.Array; - for (int i = 0; i < m; i++) - { - for (int j = 0; j < n; j++) - { - C[i][j] = A[i][j] / B.A[i][j]; - } - } - return X; - } - - public virtual GeneralMatrix ArrayRightDivideEquals(GeneralMatrix B) - { - CheckMatrixDimensions(B); - for (int i = 0; i < m; i++) - { - for (int j = 0; j < n; j++) - { - A[i][j] = A[i][j] / B.A[i][j]; - } - } - return this; - } - - public virtual GeneralMatrix ArrayLeftDivide(GeneralMatrix B) - { - CheckMatrixDimensions(B); - GeneralMatrix X = new GeneralMatrix(m, n); - decimal[][] C = X.Array; - for (int i = 0; i < m; i++) - { - for (int j = 0; j < n; j++) - { - C[i][j] = B.A[i][j] / A[i][j]; - } - } - return X; - } - - public virtual GeneralMatrix ArrayLeftDivideEquals(GeneralMatrix B) - { - CheckMatrixDimensions(B); - for (int i = 0; i < m; i++) - { - for (int j = 0; j < n; j++) - { - A[i][j] = B.A[i][j] / A[i][j]; - } - } - return this; - } - - public virtual GeneralMatrix Multiply(decimal s) - { - GeneralMatrix X = new GeneralMatrix(m, n); - decimal[][] C = X.Array; - for (int i = 0; i < m; i++) - { - for (int j = 0; j < n; j++) - { - C[i][j] = s * A[i][j]; - } - } - return X; - } - - public virtual GeneralMatrix MultiplyEquals(decimal s) - { - for (int i = 0; i < m; i++) - { - for (int j = 0; j < n; j++) - { - A[i][j] = s * A[i][j]; - } - } - return this; - } - - public virtual GeneralMatrix Multiply(GeneralMatrix B) - { - if (B.m != n) - { - throw new System.ArgumentException("GeneralMatrix inner dimensions must agree."); - } - GeneralMatrix X = new GeneralMatrix(m, B.n); - decimal[][] C = X.Array; - decimal[] Bcolj = new decimal[n]; - for (int j = 0; j < B.n; j++) - { - for (int k = 0; k < n; k++) - { - Bcolj[k] = B.A[k][j]; - } - for (int i = 0; i < m; i++) - { - decimal[] Arowi = A[i]; - decimal s = 0; - for (int k = 0; k < n; k++) - { - s += Arowi[k] * Bcolj[k]; - } - C[i][j] = s; - } - } - return X; - } - - public static GeneralMatrix operator +(GeneralMatrix m1, GeneralMatrix m2) - { - return m1.Add(m2); - } - - public static GeneralMatrix operator -(GeneralMatrix m1, GeneralMatrix m2) - { - return m1.Subtract(m2); - } - - public static GeneralMatrix operator *(GeneralMatrix m1, GeneralMatrix m2) - { - return m1.Multiply(m2); - } - - public virtual LUDecomposition LUD() - { - return new LUDecomposition(this); - } - - public virtual QRDecomposition QRD() - { - return new QRDecomposition(this); - } - - public virtual CholeskyDecomposition chol() - { - return new CholeskyDecomposition(this); - } - - public virtual SingularValueDecomposition SVD() - { - return new SingularValueDecomposition(this); - } - - public virtual EigenvalueDecomposition Eigen() - { - return new EigenvalueDecomposition(this); - } - - public virtual GeneralMatrix Solve(GeneralMatrix B) - { - return (m == n ? (new LUDecomposition(this)).Solve(B):(new QRDecomposition(this)).Solve(B)); - } - - public virtual GeneralMatrix SolveTranspose(GeneralMatrix B) - { - return Transpose().Solve(B.Transpose()); - } - - public virtual GeneralMatrix Inverse() - { - return Solve(Identity(m, m)); - } - - public virtual decimal Determinant() - { - return new LUDecomposition(this).Determinant(); - } - - public virtual int Rank() - { - return new SingularValueDecomposition(this).Rank(); - } - - public virtual decimal Condition() - { - return new SingularValueDecomposition(this).Condition(); - } - - public virtual decimal Trace() - { - decimal t = 0; - for (int i = 0; i < System.Math.Min(m, n); i++) - { - t += A[i][i]; - } - return t; - } - - public static GeneralMatrix Identity(int m, int n) - { - GeneralMatrix A = new GeneralMatrix(m, n); - decimal[][] X = A.Array; - for (int i = 0; i < m; i++) - { - for (int j = 0; j < n; j++) - { - X[i][j] = (i == j ? 1.0m : 0.0m); - } - } - return A; - } - - private void CheckMatrixDimensions(GeneralMatrix B) - { - if (B.m != m || B.n != n) - { - throw new System.ArgumentException("GeneralMatrix dimensions must agree."); - } - } - - public void Dispose() - { - Dispose(true); - } - - private void Dispose(bool disposing) - { - if (disposing) - GC.SuppressFinalize(this); - } - - ~GeneralMatrix() - { - Dispose(false); - } - - public System.Object Clone() - { - return this.Copy(); - } - - void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) - { - } - } -} diff --git a/tests/ttCalculator.Tests/LUDecomposition.cs b/tests/ttCalculator.Tests/LUDecomposition.cs deleted file mode 100644 index a30d86f..0000000 --- a/tests/ttCalculator.Tests/LUDecomposition.cs +++ /dev/null @@ -1,322 +0,0 @@ -using System; -using System.Runtime.Serialization; - -namespace DotNetMatrix -{ - - /// LU Decomposition. - /// For an m-by-n matrix A with m >= n, the LU decomposition is an m-by-n - /// unit lower triangular matrix L, an n-by-n upper triangular matrix U, - /// and a permutation vector piv of length m so that A(piv,:) = L*U. - /// If m < n, then L is m-by-m and U is m-by-n. - /// The LU decompostion with pivoting always exists, even if the matrix is - /// singular, so the constructor will never fail. The primary use of the - /// LU decomposition is in the solution of square systems of simultaneous - /// linear equations. This will fail if IsNonSingular() returns false. - /// - - [Serializable] - public class LUDecomposition : System.Runtime.Serialization.ISerializable - { - #region Class variables - - /// Array for internal storage of decomposition. - /// @serial internal array storage. - /// - private decimal[][] LU; - - /// Row and column dimensions, and pivot sign. - /// @serial column dimension. - /// @serial row dimension. - /// @serial pivot sign. - /// - private int m, n, pivsign; - - /// Internal storage of pivot vector. - /// @serial pivot vector. - /// - private int[] piv; - - #endregion // Class variables - - #region Constructor - - /// LU Decomposition - /// Rectangular matrix - /// - /// Structure to access L, U and piv. - /// - - public LUDecomposition(GeneralMatrix A) - { - // Use a "left-looking", dot-product, Crout/Doolittle algorithm. - - LU = A.ArrayCopy; - m = A.RowDimension; - n = A.ColumnDimension; - piv = new int[m]; - for (int i = 0; i < m; i++) - { - piv[i] = i; - } - pivsign = 1; - decimal[] LUrowi; - decimal[] LUcolj = new decimal[m]; - - // Outer loop. - - for (int j = 0; j < n; j++) - { - - // Make a copy of the j-th column to localize references. - - for (int i = 0; i < m; i++) - { - LUcolj[i] = LU[i][j]; - } - - // Apply previous transformations. - - for (int i = 0; i < m; i++) - { - LUrowi = LU[i]; - - // Most of the time is spent in the following dot product. - - int kmax = System.Math.Min(i, j); - decimal s = 0.0m; - for (int k = 0; k < kmax; k++) - { - s += LUrowi[k] * LUcolj[k]; - } - - LUrowi[j] = LUcolj[i] -= s; - } - - // Find pivot and exchange if necessary. - - int p = j; - for (int i = j + 1; i < m; i++) - { - if (System.Math.Abs(LUcolj[i]) > System.Math.Abs(LUcolj[p])) - { - p = i; - } - } - if (p != j) - { - for (int k = 0; k < n; k++) - { - decimal t = LU[p][k]; LU[p][k] = LU[j][k]; LU[j][k] = t; - } - int k2 = piv[p]; piv[p] = piv[j]; piv[j] = k2; - pivsign = - pivsign; - } - - // Compute multipliers. - - if (j < m & LU[j][j] != 0.0m) - { - for (int i = j + 1; i < m; i++) - { - LU[i][j] /= LU[j][j]; - } - } - } - } - #endregion // Constructor - - #region Public Properties - /// Is the matrix nonsingular? - /// true if U, and hence A, is nonsingular. - /// - virtual public bool IsNonSingular - { - get - { - for (int j = 0; j < n; j++) - { - if (LU[j][j] == 0) - return false; - } - return true; - } - } - - /// Return lower triangular factor - /// L - /// - virtual public GeneralMatrix L - { - get - { - GeneralMatrix X = new GeneralMatrix(m, n); - decimal[][] L = X.Array; - for (int i = 0; i < m; i++) - { - for (int j = 0; j < n; j++) - { - if (i > j) - { - L[i][j] = LU[i][j]; - } - else if (i == j) - { - L[i][j] = 1.0m; - } - else - { - L[i][j] = 0.0m; - } - } - } - return X; - } - } - - /// Return upper triangular factor - /// U - /// - virtual public GeneralMatrix U - { - get - { - GeneralMatrix X = new GeneralMatrix(n, n); - decimal[][] U = X.Array; - for (int i = 0; i < n; i++) - { - for (int j = 0; j < n; j++) - { - if (i <= j) - { - U[i][j] = LU[i][j]; - } - else - { - U[i][j] = 0.0m; - } - } - } - return X; - } - } - - /// Return pivot permutation vector - /// piv - /// - virtual public int[] Pivot - { - get - { - int[] p = new int[m]; - for (int i = 0; i < m; i++) - { - p[i] = piv[i]; - } - return p; - } - } - - /// Return pivot permutation vector as a one-dimensional decimal array - /// (decimal) piv - /// - virtual public decimal[] decimalPivot - { - get - { - decimal[] vals = new decimal[m]; - for (int i = 0; i < m; i++) - { - vals[i] = (decimal) piv[i]; - } - return vals; - } - } - - #endregion // Public Properties - - #region Public Methods - - /// Determinant - /// det(A) - /// - /// Matrix must be square - /// - - public virtual decimal Determinant() - { - if (m != n) - { - throw new System.ArgumentException("Matrix must be square."); - } - decimal d = (decimal) pivsign; - for (int j = 0; j < n; j++) - { - d *= LU[j][j]; - } - return d; - } - - /// Solve A*X = B - /// A Matrix with as many rows as A and any number of columns. - /// - /// X so that L*U*X = B(piv,:) - /// - /// Matrix row dimensions must agree. - /// - /// Matrix is singular. - /// - - public virtual GeneralMatrix Solve(GeneralMatrix B) - { - if (B.RowDimension != m) - { - throw new System.ArgumentException("Matrix row dimensions must agree."); - } - if (!this.IsNonSingular) - { - throw new System.SystemException("Matrix is singular."); - } - - // Copy right hand side with pivoting - int nx = B.ColumnDimension; - GeneralMatrix Xmat = B.GetMatrix(piv, 0, nx - 1); - decimal[][] X = Xmat.Array; - - // Solve L*Y = B(piv,:) - for (int k = 0; k < n; k++) - { - for (int i = k + 1; i < n; i++) - { - for (int j = 0; j < nx; j++) - { - X[i][j] -= X[k][j] * LU[i][k]; - } - } - } - // Solve U*X = Y; - for (int k = n - 1; k >= 0; k--) - { - for (int j = 0; j < nx; j++) - { - X[k][j] /= LU[k][k]; - } - for (int i = 0; i < k; i++) - { - for (int j = 0; j < nx; j++) - { - X[i][j] -= X[k][j] * LU[i][k]; - } - } - } - return Xmat; - } - - #endregion // Public Methods - - // A method called when serializing this class. - void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) - { - } - } -} diff --git a/tests/ttCalculator.Tests/Matrix.cs b/tests/ttCalculator.Tests/Matrix.cs deleted file mode 100644 index ab84f5e..0000000 --- a/tests/ttCalculator.Tests/Matrix.cs +++ /dev/null @@ -1,207 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using DotNetMatrix; - -public class Matrix -{ - private static Random random = new Random(); - - public static decimal[][] GenerateRandomMatrix(int rows, int columns, decimal min, decimal max) - { - decimal[][] res = new decimal[rows][]; - for (int i = 0; i < rows; i++) - { - res[i] = new decimal[columns]; - for (int j = 0; j < columns; j++) - { - double range = (double)(max - min); - double sample = random.NextDouble(); - double scaled = (sample * range) + (double)min; - decimal value = (decimal)System.Math.Round(scaled, 2); - res[i][j] = value; - } - } - return res; - } - - public static decimal[][] Transpoze(decimal[][] _m) - { - if (_m == null || _m.Length == 0) return new decimal[0][]; - decimal[][] res = new decimal[_m[0].Length][]; - for (int i = 0; i < _m[0].Length; i++) - { - res[i] = new decimal[_m.Length]; - } - for (int i = 0; i < _m.Length; i++) - { - for (int j = 0; j < _m[0].Length; j++) - { - res[j][i] = _m[i][j]; - } - } - return res; - } - - public static decimal MatrixDeterminant(decimal[][] _m) - { - if (_m == null || _m.Length == 0) return 0; - if (_m.Length != _m[0].Length) - { - throw new ArgumentException("Determinant hesabı için matris kare (N x N) olmalıdır."); - } - - int n = _m.Length; - if (n == 1) return _m[0][0]; - if (n == 2) return _m[0][0] * _m[1][1] - _m[0][1] * _m[1][0]; - - // Use O(n^3) LU Decomposition instead of O(n!) recursive Laplace expansion - GeneralMatrix gm = GeneralMatrix.ConstructWithCopy(_m); - return gm.Determinant(); - } - - public static decimal[] SolveEquation(decimal[][] _m, decimal[] _v) - { - if (_m == null || _v == null || _m.Length == 0) return new decimal[0]; - int len = _m.Length; - - GeneralMatrix A = GeneralMatrix.ConstructWithCopy(_m); - GeneralMatrix b = new GeneralMatrix(len, 1); - for (int i = 0; i < len; i++) - { - b.Array[i][0] = _v[i]; - } - - GeneralMatrix x = A.Solve(b); - decimal[] res = new decimal[len]; - for (int i = 0; i < len; i++) - { - res[i] = x.Array[i][0]; - } - return res; - } - - public static decimal[][] ConvertLinearEquationsToMatrix(List equations, List variables) - { - if (equations == null || variables == null || equations.Count != variables.Count) return null; - - int n = equations.Count; - decimal[][] res = new decimal[n][]; - for (int i = 0; i < n; i++) - { - res[i] = new decimal[n]; - string eq = equations[i]; - if (eq.Contains("=")) - { - string[] parts = eq.Split('='); - eq = parts[0] + "-(" + parts[1] + ")"; - } - - // Use numerical evaluation to extract exact linear coefficients reliably: - // f(0, 0, ...) = c - // f(0, ..., x_k=1, ..., 0) - c = coeff_k - Dictionary zeroPts = new Dictionary(); - foreach (string v in variables) zeroPts[v] = 0m; - - decimal f0 = NumericalMethods.MethodMultiVar_EvaluateFunction(eq, zeroPts); - - for (int k = 0; k < n; k++) - { - string varName = variables[k]; - zeroPts[varName] = 1m; - decimal f1 = NumericalMethods.MethodMultiVar_EvaluateFunction(eq, zeroPts); - res[i][k] = f1 - f0; - zeroPts[varName] = 0m; - } - } - return res; - } - - public static decimal[][] MatrixMultiplication(decimal[][] _m1, decimal[][] _m2) - { - if (_m1 == null || _m2 == null || _m1.Length == 0 || _m2.Length == 0) return null; - if (_m1[0].Length == _m2.Length) - { - decimal[][] res = new decimal[_m1.Length][]; - for (int i = 0; i < _m1.Length; i++) - { - res[i] = new decimal[_m2[0].Length]; - } - - for (int i = 0; i < res.Length; i++) - { - for (int j = 0; j < res[0].Length; j++) - { - decimal sum = 0; - for (int k = 0; k < _m2.Length; k++) - { - sum += _m1[i][k] * _m2[k][j]; - } - res[i][j] = sum; - } - } - return res; - } - else - { - throw new ArgumentException("Birinci matrisin sütun sayısı ile ikinci matrisin satır sayısı eşit olmalıdır."); - } - } - - public static decimal[][] MatrixMultiplication(decimal[][] _m, decimal _c) - { - if (_m == null) return null; - decimal[][] res = new decimal[_m.Length][]; - for (int i = 0; i < _m.Length; i++) - { - res[i] = new decimal[_m[i].Length]; - for (int j = 0; j < _m[i].Length; j++) - { - res[i][j] = _m[i][j] * _c; - } - } - return res; - } - - public static decimal[] TurnListToVector(List _vec) - { - return _vec.ToArray(); - } - - public static decimal[][] TurnListToMatrix(List> _m) - { - decimal[][] res = new decimal[_m.Count][]; - for (int i = 0; i < _m.Count; i++) - { - res[i] = _m[i].ToArray(); - } - return res; - } - - public static string DebugMatrix(decimal[][] _m, string _sep = "\t") - { - if (_m == null || _m.Length == 0) return ""; - System.Text.StringBuilder sb = new System.Text.StringBuilder(); - for (int i = 0; i < _m.Length; i++) - { - for (int j = 0; j < _m[i].Length; j++) - { - sb.Append(_m[i][j].ToString("0.######", CultureInfo.InvariantCulture)); - sb.Append(j == _m[i].Length - 1 ? Environment.NewLine : _sep); - } - } - return sb.ToString(); - } - - public static string DebugVector(decimal[] _v, string _sep = " ") - { - if (_v == null) return ""; - System.Text.StringBuilder sb = new System.Text.StringBuilder(); - for (int i = 0; i < _v.Length; i++) - { - sb.AppendLine(_v[i].ToString("0.######", CultureInfo.InvariantCulture)); - } - return sb.ToString(); - } -} diff --git a/tests/ttCalculator.Tests/NumericalMethods.cs b/tests/ttCalculator.Tests/NumericalMethods.cs deleted file mode 100644 index ec2bacd..0000000 --- a/tests/ttCalculator.Tests/NumericalMethods.cs +++ /dev/null @@ -1,1114 +0,0 @@ -using DotNetMatrix; -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Text; -using System.Text.RegularExpressions; - -public class NumericalMethods -{ - public static string NormalizeEquation(string eq) - { - if (string.IsNullOrWhiteSpace(eq)) return ""; - eq = eq.Trim(); - if (eq.Contains("=")) - { - string[] parts = eq.Split('='); - if (parts.Length == 2 && !string.IsNullOrWhiteSpace(parts[1])) - { - return "(" + parts[0] + ")-(" + parts[1] + ")"; - } - } - return eq; - } - - public static Function CompileFunction(string eq) - { - string norm = NormalizeEquation(eq); - Function f = new Function(); - f.Parse(norm); - if (f.Error) - { - throw new ArgumentException("Denklem ayrıştırma hatası: " + f.ErrorDescription); - } - f.Infix2Postfix(); - return f; - } - - public static decimal EvaluateCompiled(Function f, string variable, decimal point) - { - f.SetVariable(variable, point); - f.EvaluatePostfix(); - if (f.Error) - { - throw new ArithmeticException(f.ErrorDescription); - } - return f.Result; - } - - public static decimal EvaluateCompiledMultiVar(Function f, Dictionary points) - { - f.SetVariables(points); - f.EvaluatePostfix(); - if (f.Error) - { - throw new ArithmeticException(f.ErrorDescription); - } - return f.Result; - } - - public static decimal Method_EvaluateFunction(string eq, string variable, decimal point) - { - Function f = CompileFunction(eq); - return EvaluateCompiled(f, variable, point); - } - - public static decimal MethodMultiVar_EvaluateFunction(string eq, Dictionary points) - { - Function f = CompileFunction(eq); - return EvaluateCompiledMultiVar(f, points); - } - - /// - /// Solves a nonlinear or linear system of equations using Multivariable Newton-Raphson with analytical/numerical Jacobian - /// and returns step-by-step convergence logs as well as the final solution dictionary. - /// - public static Dictionary MethodMultiVar_SolveEquationSystem( - List eqs, - Dictionary initPoints, - int iterationCount = 50, - decimal h = 0.0001m) - { - var logs = new List(); - return SolveEquationSystemWithLogs(eqs, initPoints, iterationCount, out logs, h); - } - - public static Dictionary SolveEquationSystemWithLogs( - List eqs, - Dictionary initPoints, - int iterationCount, - out List logs, - decimal h = 0.0001m) - { - logs = new List(); - if (eqs == null || initPoints == null || eqs.Count == 0 || eqs.Count != initPoints.Count) - { - throw new ArgumentException("Denklem sayısı ile değişken sayısı birbirine eşit olmalıdır."); - } - - int n = eqs.Count; - List vars = initPoints.Keys.ToList(); - Dictionary currentPoints = new Dictionary(initPoints); - - List compiledEqs = new List(n); - for (int i = 0; i < n; i++) - { - compiledEqs.Add(CompileFunction(eqs[i])); - } - - decimal tolerance = 0.0000000001m; // 1e-10m - - for (int iter = 1; iter <= iterationCount; iter++) - { - decimal[] F = new decimal[n]; - decimal maxAbsF = 0m; - - for (int i = 0; i < n; i++) - { - F[i] = EvaluateCompiledMultiVar(compiledEqs[i], currentPoints); - decimal absF = DecimalMath.Abs(F[i]); - if (absF > maxAbsF) maxAbsF = absF; - } - - if (maxAbsF <= tolerance) - { - logs.Add($"[Adım {iter - 1}] Yakınsama sağlandı! Maksimum hata |F| = {maxAbsF:E4}"); - break; - } - - // Compute Jacobian Matrix J[i][j] = df_i / dx_j via central finite difference - decimal[][] J = new decimal[n][]; - for (int i = 0; i < n; i++) - { - J[i] = new decimal[n]; - for (int j = 0; j < n; j++) - { - string vName = vars[j]; - decimal origVal = currentPoints[vName]; - - currentPoints[vName] = origVal + h; - decimal fPlus = EvaluateCompiledMultiVar(compiledEqs[i], currentPoints); - - currentPoints[vName] = origVal - h; - decimal fMinus = EvaluateCompiledMultiVar(compiledEqs[i], currentPoints); - - currentPoints[vName] = origVal; - J[i][j] = (fPlus - fMinus) / (2m * h); - } - } - - decimal[] negF = new decimal[n]; - for (int i = 0; i < n; i++) negF[i] = -F[i]; - - decimal[] delta; - try - { - delta = Matrix.SolveEquation(J, negF); - } - catch - { - // Perturb slightly if Jacobian is singular at initial guess (e.g. (0,0) for x^2+y^2) - for (int j = 0; j < n; j++) - { - currentPoints[vars[j]] += 0.01m * (j + 1); - } - logs.Add($"[Adım {iter}] Jakobiyen matrisi tekil (singular) noktaya denk geldi, nokta hafifçe kaydırılıyor..."); - continue; - } - - decimal maxStep = 0m; - for (int j = 0; j < n; j++) - { - currentPoints[vars[j]] += delta[j]; - decimal absD = DecimalMath.Abs(delta[j]); - if (absD > maxStep) maxStep = absD; - } - - string ptSummary = string.Join(", ", vars.Select(v => $"{v} = {currentPoints[v].ToString("0.########", CultureInfo.InvariantCulture)}")); - logs.Add($"[Adım {iter}] {ptSummary} (|Δ| = {maxStep:E3})"); - - if (maxStep <= tolerance) - { - logs.Add($"[Adım {iter}] Çözüm başarıyla yakınsadı."); - break; - } - } - - return currentPoints; - } - - public static string Method_TaylorSeries(string eq, int degree, string variable, decimal point, decimal h = 0.005m) - { - if (string.IsNullOrWhiteSpace(variable)) variable = "x"; - decimal constant = Method_EvaluateFunction(eq, variable, point); - if (DecimalMath.Abs(constant) <= 0.000001m) constant = 0; - - List terms = new List(); - if (constant != 0) - { - terms.Add(FormatCoeff(constant)); - } - - for (int i = 1; i <= degree; i++) - { - decimal step = i >= 4 ? 0.01m : h; - decimal der = Method_NumericalDifferentiation(eq, i, variable, point, 4, step); - decimal fact = Factorial(i); - decimal coeff = der / fact; - - if (DecimalMath.Abs(coeff) <= 0.000001m) continue; - - string varPart = FormatVarPower(variable, point, i); - string coeffStr = FormatTermWithCoeff(coeff, varPart, terms.Count == 0); - terms.Add(coeffStr); - } - - if (terms.Count == 0) return "0"; - return string.Join(" ", terms); - } - - public static string MethodMultiVar_TaylorSeries(string eq, int degree, Dictionary points, decimal h = 0.005m) - { - if (points == null || points.Count == 0) return "0"; - - Function compiled = CompileFunction(eq); - decimal constant = EvaluateCompiledMultiVar(compiled, points); - if (DecimalMath.Abs(constant) <= 0.00001m) constant = 0; - - List terms = new List(); - if (constant != 0) - { - terms.Add(FormatCoeff(constant)); - } - - List varNames = points.Keys.ToList(); - int kVars = varNames.Count; - - for (int totalDeg = 1; totalDeg <= degree; totalDeg++) - { - List multiIndices = GenerateMultiIndices(kVars, totalDeg); - foreach (int[] alpha in multiIndices) - { - decimal mixedDer = ComputeMixedPartialDerivative(compiled, varNames, alpha, points, h); - decimal denom = 1m; - for (int j = 0; j < kVars; j++) - { - denom *= Factorial(alpha[j]); - } - - decimal coeff = mixedDer / denom; - if (DecimalMath.Abs(coeff) <= 0.00001m) continue; - - List factors = new List(); - for (int j = 0; j < kVars; j++) - { - if (alpha[j] > 0) - { - string vName = varNames[j]; - factors.Add(FormatVarPower(vName, points[vName], alpha[j])); - } - } - - string varPart = string.Join(" * ", factors); - terms.Add(FormatTermWithCoeff(coeff, varPart, terms.Count == 0)); - } - } - - if (terms.Count == 0) return "0"; - return string.Join(" ", terms); - } - - private static List GenerateMultiIndices(int numVars, int totalSum) - { - List results = new List(); - int[] current = new int[numVars]; - GenerateMultiIndicesRecursive(numVars, totalSum, 0, current, results); - return results; - } - - private static void GenerateMultiIndicesRecursive(int numVars, int remaining, int idx, int[] current, List results) - { - if (idx == numVars - 1) - { - current[idx] = remaining; - results.Add((int[])current.Clone()); - return; - } - for (int v = remaining; v >= 0; v--) - { - current[idx] = v; - GenerateMultiIndicesRecursive(numVars, remaining - v, idx + 1, current, results); - } - } - - private static decimal ComputeMixedPartialDerivative( - Function f, - List varNames, - int[] orders, - Dictionary basePoints, - decimal h) - { - Dictionary workPoints = new Dictionary(basePoints); - return ComputeMixedRecursive(f, varNames, orders, 0, workPoints, h); - } - - private static decimal ComputeMixedRecursive( - Function f, - List varNames, - int[] orders, - int varIndex, - Dictionary workPoints, - decimal h) - { - while (varIndex < orders.Length && orders[varIndex] == 0) - { - varIndex++; - } - - if (varIndex >= orders.Length) - { - return EvaluateCompiledMultiVar(f, workPoints); - } - - string vName = varNames[varIndex]; - int m = orders[varIndex]; - decimal origVal = workPoints[vName]; - - // Central finite difference weights for order m - decimal sum = 0m; - for (int i = 0; i <= m; i++) - { - decimal shift = (m - 2m * i) * (h * 0.5m); - workPoints[vName] = origVal + shift; - decimal sign = (i % 2 == 0) ? 1m : -1m; - decimal comb = Combination(m, i); - decimal subVal = ComputeMixedRecursive(f, varNames, orders, varIndex + 1, workPoints, h); - sum += sign * comb * subVal; - } - - workPoints[vName] = origVal; - return sum / DecimalMath.Pow(h, m); - } - - private static string FormatCoeff(decimal c) - { - decimal rounded = Math.Round(c, 6); - foreach (int denom in new[] { 1, 2, 3, 4, 6, 8, 12 }) - { - decimal candidate = Math.Round(c * denom) / (decimal)denom; - if (DecimalMath.Abs(c - candidate) < 0.00005m) - { - rounded = candidate; - break; - } - } - return rounded.ToString("0.######", CultureInfo.InvariantCulture); - } - - private static string FormatVarPower(string variable, decimal center, int power) - { - string core; - if (center == 0m) - { - core = variable; - } - else if (center > 0m) - { - core = $"({variable} - {FormatCoeff(center)})"; - } - else - { - core = $"({variable} + {FormatCoeff(DecimalMath.Abs(center))})"; - } - - if (power == 1) return core; - return $"{core}^{power}"; - } - - private static string FormatTermWithCoeff(decimal coeff, string varPart, bool isFirst) - { - decimal absC = DecimalMath.Abs(coeff); - string sign = coeff < 0 ? (isFirst ? "-" : "- ") : (isFirst ? "" : "+ "); - string cStr = FormatCoeff(absC); - - if (cStr == "1") - { - return $"{sign}{varPart}"; - } - return $"{sign}{cStr}*{varPart}"; - } - - public static decimal Method_NewtonRaphson(string eq, string variable, decimal initialValue, int iterationCount, decimal h = 0.0001m) - { - Function f = CompileFunction(eq); - decimal curr = initialValue; - for (int i = 0; i < iterationCount; i++) - { - decimal fx = EvaluateCompiled(f, variable, curr); - if (DecimalMath.Abs(fx) <= 1e-12m) break; - - decimal dfx = (EvaluateCompiled(f, variable, curr + h) - EvaluateCompiled(f, variable, curr - h)) / (2m * h); - if (DecimalMath.Abs(dfx) <= 1e-15m) break; - - curr = curr - fx / dfx; - } - return curr; - } - - public static decimal Method_BisectionMethod(string eq, string variable, decimal lowerValue, decimal higherValue, int iterationCount) - { - if (lowerValue >= higherValue) return lowerValue; - - Function f = CompileFunction(eq); - decimal fa = EvaluateCompiled(f, variable, lowerValue); - if (DecimalMath.Abs(fa) <= 1e-12m) return lowerValue; - decimal fb = EvaluateCompiled(f, variable, higherValue); - if (DecimalMath.Abs(fb) <= 1e-12m) return higherValue; - - decimal mp = (lowerValue + higherValue) / 2m; - - for (int i = 0; i < iterationCount; i++) - { - mp = (lowerValue + higherValue) / 2m; - decimal evMiddle = EvaluateCompiled(f, variable, mp); - - if (DecimalMath.Abs(evMiddle) <= 1e-12m) break; - - if (fa * evMiddle <= 0) - { - higherValue = mp; - fb = evMiddle; - } - else - { - lowerValue = mp; - fa = evMiddle; - } - } - - return mp; - } - - public static decimal Method_Derivative(string eq, int degree, string variable, decimal point, decimal h = 0.001m) - { - return Method_NumericalDifferentiation(eq, degree, variable, point, 4, h); - } - - public static decimal Method_PartialDerivative(string eq, int degree, string toVar, Dictionary points, decimal h = 0.001m) - { - return Method_NumericalPartialDifferentiation(eq, degree, toVar, points, 4, h); - } - - public static decimal Method_NumericalDifferentiation(string eq, int degree, string variable, decimal point, int accuracy = 2, decimal h = 0.001m) - { - int m = degree, n = accuracy; - if (m >= 11) { n = 2; h = 0.08m; } - else if (m == 10) { n = 2; h = 0.04m; } - else if (m == 9) { n = 4; h = 0.015m; } - else if (m >= 7 && h < 0.012m) h = 0.012m; - - Function f = CompileFunction(eq); - int p = (2 * (int)Math.Floor((m + 1) / 2.0) - 2 + n) / 2; - - decimal[][] _matrix = new decimal[2 * p + 1][]; - decimal[] _rhsVector = new decimal[2 * p + 1], functionPointsX = new decimal[2 * p + 1], - functionPointsY = new decimal[2 * p + 1]; - - for (int i = 0; i < _matrix.Length; i++) - { - _matrix[i] = new decimal[2 * p + 1]; - for (int j = 0; j < _matrix[i].Length; j++) - { - _matrix[i][j] = DecimalMath.PowerN(-p + j, i); - } - - _rhsVector[i] = (i == m) ? Factorial(m) : 0m; - functionPointsX[i] = point - (p - i) * h; - functionPointsY[i] = EvaluateCompiled(f, variable, functionPointsX[i]); - } - - GeneralMatrix _A = new GeneralMatrix(_matrix); - GeneralMatrix _b = new GeneralMatrix(_rhsVector.Length, 1); - - for (int i = 0; i < _rhsVector.Length; i++) - { - _b.Array[i][0] = _rhsVector[i]; - } - - GeneralMatrix coeffs = _A.Solve(_b); - decimal sum = 0; - - for (int i = 0; i < coeffs.Array.Length; i++) - { - sum += coeffs.Array[i][0] * functionPointsY[i]; - } - - return sum / DecimalMath.Pow(h, degree); - } - - public static decimal Method_NumericalPartialDifferentiation(string eq, int degree, string toVar, Dictionary points, int accuracy = 2, decimal h = 0.001m) - { - Function f = CompileFunction(eq); - int m = degree, n = accuracy; - int p = (2 * (int)Math.Floor((m + 1) / 2.0) - 2 + n) / 2; - - decimal[][] _matrix = new decimal[2 * p + 1][]; - Dictionary functionPointsDomain = new Dictionary(); - decimal[] _rhsVector = new decimal[2 * p + 1], functionPointsRange = new decimal[2 * p + 1]; - - for (int i = 0; i < _matrix.Length; i++) - { - _matrix[i] = new decimal[2 * p + 1]; - for (int j = 0; j < _matrix[i].Length; j++) - { - _matrix[i][j] = DecimalMath.PowerN(-p + j, i); - } - - _rhsVector[i] = (i == m) ? Factorial(m) : 0m; - } - - foreach (KeyValuePair item in points) - { - decimal[] ps = new decimal[2 * p + 1]; - if (item.Key == toVar) - { - for (int i = 0; i < ps.Length; i++) ps[i] = points[item.Key] - (p - i) * h; - } - else - { - for (int i = 0; i < ps.Length; i++) ps[i] = points[item.Key]; - } - functionPointsDomain.Add(item.Key, ps); - } - - for (int i = 0; i < 2 * p + 1; i++) - { - Dictionary pair = new Dictionary(); - foreach (KeyValuePair item in functionPointsDomain) - { - pair.Add(item.Key, item.Value[i]); - } - functionPointsRange[i] = EvaluateCompiledMultiVar(f, pair); - } - - GeneralMatrix _A = new GeneralMatrix(_matrix); - GeneralMatrix _b = new GeneralMatrix(_rhsVector.Length, 1); - - for (int i = 0; i < _rhsVector.Length; i++) _b.Array[i][0] = _rhsVector[i]; - - GeneralMatrix coeffs = _A.Solve(_b); - decimal sum = 0; - - for (int i = 0; i < coeffs.Array.Length; i++) - { - sum += coeffs.Array[i][0] * functionPointsRange[i]; - } - - return sum / DecimalMath.Pow(h, degree); - } - - public static decimal Factorial(int num) - { - if (num < 0) return 0m; - decimal res = 1m; - for (int i = 2; i <= num; i++) res *= i; - return res; - } - - public static decimal Combination(int n, int k) - { - if (k < 0 || k > n || n < 0) return 0m; - if (k == 0 || k == n) return 1m; - if (k > n - k) k = n - k; - decimal res = 1m; - for (int i = 1; i <= k; i++) - { - res = (res * (n - k + i)) / i; - } - return res; - } - - public static decimal Permutation(int n, int k) - { - if (k < 0 || k > n || n < 0) return 0m; - if (k == 0) return 1m; - decimal res = 1m; - for (int i = 0; i < k; i++) - { - res *= (n - i); - } - return res; - } - - public static string GenerateCombinations(string chars, string prefix, int length) - { - StringBuilder sb = new StringBuilder(); - GenerateCombinationsRecursive(prefix, chars, length, sb); - return sb.ToString(); - } - - static void GenerateCombinationsRecursive(string prefix, string chars, int length, StringBuilder sb) - { - if (length == 0) - { - sb.AppendLine(prefix); - return; - } - - foreach (char c in chars) - { - GenerateCombinationsRecursive(prefix + c, chars, length - 1, sb); - } - } - - /// - /// Gauss-Seidel Iterative Linear System Solver with Diagonal Dominance Verification & Row Reordering. - /// Ported and enhanced from NumericalMethods / NumericalMethods2. - /// - public static Dictionary Method_GaussSeidel( - List eqs, - Dictionary initPoints, - int iterationCount, - out List logs) - { - logs = new List(); - if (eqs == null || initPoints == null || eqs.Count == 0 || eqs.Count != initPoints.Count) - { - throw new ArgumentException("Denklem sayısı ile değişken sayısı birbirine eşit olmalıdır."); - } - - int n = eqs.Count; - List vars = initPoints.Keys.ToList(); - - // Extract linear matrix A and right-hand vector b such that A * x = b - // Note: ConvertLinearEquationsToMatrix evaluates f(x) = LHS - RHS = A*x - b - decimal[][] A = Matrix.ConvertLinearEquationsToMatrix(eqs, vars); - decimal[] b = new decimal[n]; - Dictionary zeroPts = new Dictionary(); - foreach (string v in vars) zeroPts[v] = 0m; - - for (int i = 0; i < n; i++) - { - string normEq = NormalizeEquation(eqs[i]); - // f(0) = -b => b = -f(0) - b[i] = -MethodMultiVar_EvaluateFunction(normEq, zeroPts); - } - - // Check / reorder rows for diagonal dominance: |a_ii| > sum_{j != i} |a_ij| - int[] dominantColForRow = new int[n]; - bool strictDominance = true; - for (int i = 0; i < n; i++) - { - int domCol = -1; - for (int j = 0; j < n; j++) - { - decimal sumOthers = 0m; - for (int k = 0; k < n; k++) - { - if (k != j) sumOthers += DecimalMath.Abs(A[i][k]); - } - if (DecimalMath.Abs(A[i][j]) >= sumOthers && DecimalMath.Abs(A[i][j]) > 0m) - { - domCol = j; - break; - } - } - dominantColForRow[i] = domCol; - if (domCol == -1) strictDominance = false; - } - - // Attempt to permute rows if each row has a distinct dominant column - if (strictDominance && dominantColForRow.Distinct().Count() == n) - { - decimal[][] newA = new decimal[n][]; - decimal[] newB = new decimal[n]; - for (int i = 0; i < n; i++) - { - int targetRow = dominantColForRow[i]; - newA[targetRow] = A[i]; - newB[targetRow] = b[i]; - } - A = newA; - b = newB; - logs.Add("✓ Köşegen baskınlığı (Diagonal Dominance) doğrulandı (|a_ii| ≥ Σ|a_ij|)."); - } - else - { - logs.Add("⚠️ Uyarı: Matris tam köşegen baskın değil; Gauss-Seidel yakınsamayabilir."); - } - - decimal[] x = new decimal[n]; - for (int i = 0; i < n; i++) x[i] = initPoints[vars[i]]; - - decimal tol = 1e-10m; - for (int iter = 1; iter <= iterationCount; iter++) - { - decimal maxDiff = 0m; - for (int i = 0; i < n; i++) - { - if (DecimalMath.Abs(A[i][i]) <= 1e-15m) - { - throw new ArithmeticException($"Köşegen elemanı A[{i + 1},{i + 1}] = 0 olduğu için Gauss-Seidel uygulanamaz."); - } - - decimal sigma = 0m; - for (int j = 0; j < n; j++) - { - if (j != i) sigma += A[i][j] * x[j]; - } - - decimal nextXi = (b[i] - sigma) / A[i][i]; - decimal diff = DecimalMath.Abs(nextXi - x[i]); - if (diff > maxDiff) maxDiff = diff; - x[i] = nextXi; - } - - string stepStr = string.Join(", ", Enumerable.Range(0, n).Select(idx => $"{vars[idx]} = {x[idx].ToString("0.########", CultureInfo.InvariantCulture)}")); - logs.Add($"[Adım {iter,2}] {stepStr} (|Δ| = {maxDiff:E3})"); - - if (maxDiff <= tol) - { - logs.Add($"✓ Gauss-Seidel {iter}. adımda başarıyla yakınsadı."); - break; - } - } - - Dictionary result = new Dictionary(); - for (int i = 0; i < n; i++) result[vars[i]] = x[i]; - return result; - } - - public static Dictionary Method_LinearMatrixSolve( - List eqs, - List vars, - string methodType, - out List logs) - { - logs = new List(); - int n = eqs.Count; - decimal[][] A = Matrix.ConvertLinearEquationsToMatrix(eqs, vars); - decimal[] b = new decimal[n]; - - Dictionary zeroPts = new Dictionary(); - foreach (string v in vars) zeroPts[v] = 0m; - bool isNonLinear = false; - for (int i = 0; i < n; i++) - { - string normEq = NormalizeEquation(eqs[i]); - b[i] = -MethodMultiVar_EvaluateFunction(normEq, zeroPts); - - if (vars.Count > 0) - { - zeroPts[vars[0]] = 2m; - decimal f2 = MethodMultiVar_EvaluateFunction(normEq, zeroPts); - zeroPts[vars[0]] = 0m; - if (DecimalMath.Abs(f2 - (2m * A[i][0] - b[i])) > 1e-4m) - { - isNonLinear = true; - } - } - } - - if (isNonLinear) - { - logs.Add("UYARI: Denklemler doğrusal değil. Çözüm doğrusal yaklaşım olarak sunulmuştur."); - } - - logs.Add("--- Katsayılar Matrisi (A) ve Sağ Taraf Vektörü (b) ---"); - for (int i = 0; i < n; i++) - { - string rowStr = string.Join(" ", A[i].Select(v => $"{v,8:0.####}")); - logs.Add($" [ {rowStr} ] | [ {b[i],8:0.####} ]"); - } - logs.Add(""); - - GeneralMatrix gA = new GeneralMatrix(A); - GeneralMatrix gB = new GeneralMatrix(n, 1); - for (int i = 0; i < n; i++) gB.Array[i][0] = b[i]; - - GeneralMatrix gX; - if (methodType == "INVERSE") - { - logs.Add("Yöntem: Ters Matris (X = A⁻¹ · b)"); - GeneralMatrix invA = gA.Inverse(); - gX = invA.Multiply(gB); - } - else if (methodType == "QR") - { - logs.Add("Yöntem: QR Ayrışımı (Q·R·X = b)"); - gX = gA.QRD().Solve(gB); - } - else - { - logs.Add("Yöntem: LU Ayrışımı (L·U·X = P·b)"); - gX = gA.LUD().Solve(gB); - } - - Dictionary res = new Dictionary(); - for (int i = 0; i < n; i++) - { - res[vars[i]] = gX.Array[i][0]; - logs.Add($" {vars[i]} = {Math.Round(gX.Array[i][0], 8).ToString("0.########", CultureInfo.InvariantCulture)}"); - } - return res; - } - - public static decimal Method_BackwardDifferenceDerivative(string eq, int degree, string variable, decimal point, decimal h = 0.001m) - { - Function f = CompileFunction(eq); - decimal f0 = EvaluateCompiled(f, variable, point); - decimal f1 = EvaluateCompiled(f, variable, point - h); - decimal f2 = EvaluateCompiled(f, variable, point - 2m * h); - - if (degree == 1) - { - return (3m * f0 + f2 - 4m * f1) / (2m * h); - } - else if (degree == 2) - { - return (f0 + f2 - 2m * f1) / (h * h); - } - else if (degree == 3) - { - decimal f3 = EvaluateCompiled(f, variable, point - 3m * h); - decimal f4 = EvaluateCompiled(f, variable, point - 4m * h); - return (3m * f4 - 14m * f3 + 24m * f2 - 18m * f1 + 5m * f0) / (2m * h * h * h); - } - else if (degree == 4) - { - decimal f3 = EvaluateCompiled(f, variable, point - 3m * h); - decimal f4 = EvaluateCompiled(f, variable, point - 4m * h); - decimal f5 = EvaluateCompiled(f, variable, point - 5m * h); - return (-2m * f5 + 11m * f4 - 24m * f3 + 26m * f2 - 14m * f1 + 3m * f0) / (h * h * h * h); - } - else - { - return Method_ForwardBinomialDerivative(eq, degree, variable, point, h); - } - } - - public static decimal Method_ForwardBinomialDerivative(string eq, int degree, string variable, decimal point, decimal h = 0.001m) - { - Function f = CompileFunction(eq); - decimal sum = 0m; - for (int i = 0; i <= degree; i++) - { - decimal sign = (i % 2 == 0) ? 1m : -1m; - sum += sign * Combination(degree, i) * EvaluateCompiled(f, variable, point + (degree - i) * h); - } - return sum / DecimalMath.Pow(h, degree); - } - - public static decimal Method_ForwardBinomialPartialDerivative(string eq, int degree, string toVar, Dictionary points, decimal h = 0.001m) - { - Function f = CompileFunction(eq); - decimal sum = 0m; - Dictionary testPS = new Dictionary(points); - decimal firstToVar = testPS[toVar]; - for (int i = 0; i <= degree; i++) - { - testPS[toVar] = firstToVar + (degree - i) * h; - decimal sign = (i % 2 == 0) ? 1m : -1m; - sum += sign * Combination(degree, i) * EvaluateCompiledMultiVar(f, testPS); - } - return sum / DecimalMath.Pow(h, degree); - } - - // --- Root Finding Methods with Full Iteration Logs & Variable Support --- - - public static List Method_NewtonRaphson(string _eq, decimal _initialPoint, int _iterationCount, string variable = "x") - { - if (string.IsNullOrWhiteSpace(variable)) variable = "x"; - Function f = CompileFunction(_eq); - List logs = new List(); - decimal x = _initialPoint; - decimal h = 0.0001m; - decimal tol = 1e-12m; - - logs.Add($"--- Newton-Raphson Yöntemi (Başlangıç: {variable}₀ = {x.ToString(CultureInfo.InvariantCulture)}) ---"); - - for (int i = 1; i <= _iterationCount; i++) - { - decimal fx = EvaluateCompiled(f, variable, x); - decimal dfx = (EvaluateCompiled(f, variable, x + h) - EvaluateCompiled(f, variable, x - h)) / (2m * h); - - if (DecimalMath.Abs(dfx) <= 1e-15m) - { - logs.Add($"[Adım {i}] Türev sıfıra çok yakın (f'({variable}) ≈ 0). İşlem durduruldu."); - break; - } - - decimal nextX = x - fx / dfx; - decimal err = DecimalMath.Abs(nextX - x); - x = nextX; - - logs.Add($"[Adım {i,2}] {variable} = {x.ToString("0.############", CultureInfo.InvariantCulture),-18} | f({variable}) = {fx.ToString("E3", CultureInfo.InvariantCulture),-11} | |Δ| = {err.ToString("E3", CultureInfo.InvariantCulture)}"); - - if (err <= tol || DecimalMath.Abs(fx) <= tol) - { - logs.Add($"✓ Yakınsama {i}. adımda tamamlandı."); - break; - } - } - - decimal finalFx = EvaluateCompiled(f, variable, x); - logs.Add(""); - logs.Add($">>> BULUNAN KÖK: {variable} = {x.ToString("0.##########", CultureInfo.InvariantCulture)} (f({variable}) = {finalFx.ToString("0.##########", CultureInfo.InvariantCulture)})"); - return logs; - } - - public static List Method_Bisection(string _eq, decimal _min, decimal _max, int _iterationCount, string variable = "x") - { - if (string.IsNullOrWhiteSpace(variable)) variable = "x"; - Function f = CompileFunction(_eq); - List logs = new List(); - - decimal a = _min; - decimal b = _max; - if (a >= b) - { - return new List { "Hata: Alt sınır (Min) üst sınırdan (Max) küçük olmalıdır." }; - } - - decimal fa = EvaluateCompiled(f, variable, a); - decimal fb = EvaluateCompiled(f, variable, b); - - if (DecimalMath.Abs(fa) <= 1e-12m) - { - logs.Add($"✓ Alt sınır {variable} = {a} zaten bir köktür: f({a}) = {fa}"); - logs.Add($">>> BULUNAN KÖK: {variable} = {a.ToString("0.##########", CultureInfo.InvariantCulture)} (f({variable}) = 0)"); - return logs; - } - if (DecimalMath.Abs(fb) <= 1e-12m) - { - logs.Add($"✓ Üst sınır {variable} = {b} zaten bir köktür: f({b}) = {fb}"); - logs.Add($">>> BULUNAN KÖK: {variable} = {b.ToString("0.##########", CultureInfo.InvariantCulture)} (f({variable}) = 0)"); - return logs; - } - - if (fa * fb > 0) - { - return new List - { - $"Uyarı: Seçilen [{a}, {b}] aralığında işaret değişimi yok!", - $"f({a}) = {fa:0.######} ve f({b}) = {fb:0.######} aynı işaretli.", - "Bisection (İkiye Bölme) yöntemi için f(Min) * f(Max) <= 0 olmalıdır." - }; - } - - logs.Add($"--- Bisection (İkiye Bölme) Yöntemi [{a}, {b}] ---"); - decimal mid = (a + b) / 2m; - decimal tol = 1e-11m; - - for (int i = 1; i <= _iterationCount; i++) - { - mid = (a + b) / 2m; - decimal fMid = EvaluateCompiled(f, variable, mid); - decimal width = (b - a) / 2m; - - logs.Add($"[Adım {i,2}] {variable} = {mid.ToString("0.############", CultureInfo.InvariantCulture),-18} | f({variable}) = {fMid.ToString("E3", CultureInfo.InvariantCulture),-11} | Aralık: [{a:0.####}, {b:0.####}]"); - - if (DecimalMath.Abs(fMid) <= tol || width <= tol) - { - logs.Add($"✓ Yakınsama {i}. adımda tamamlandı."); - break; - } - - if (fa * fMid <= 0) - { - b = mid; - fb = fMid; - } - else - { - a = mid; - fa = fMid; - } - } - - decimal finalFx = EvaluateCompiled(f, variable, mid); - logs.Add(""); - logs.Add($">>> BULUNAN KÖK: {variable} = {mid.ToString("0.##########", CultureInfo.InvariantCulture)} (f({variable}) = {finalFx.ToString("0.##########", CultureInfo.InvariantCulture)})"); - return logs; - } - - public static List Method_Secant(string _eq, decimal _min, decimal _max, int _iterationCount, string variable = "x") - { - if (string.IsNullOrWhiteSpace(variable)) variable = "x"; - Function f = CompileFunction(_eq); - List logs = new List(); - - decimal x0 = _min; - decimal x1 = _max; - decimal x2 = x1; - decimal tol = 1e-11m; - - logs.Add($"--- Secant (Kiriş) Yöntemi ({variable}₀ = {x0}, {variable}₁ = {x1}) ---"); - - for (int i = 1; i <= _iterationCount; i++) - { - decimal f0 = EvaluateCompiled(f, variable, x0); - decimal f1 = EvaluateCompiled(f, variable, x1); - - if (DecimalMath.Abs(f1 - f0) <= 1e-15m) - { - logs.Add($"[Adım {i}] f({variable}₁) - f({variable}₀) ≈ 0 oldu. İşlem durduruldu."); - break; - } - - x2 = x1 - f1 * (x1 - x0) / (f1 - f0); - decimal err = DecimalMath.Abs(x2 - x1); - x0 = x1; - x1 = x2; - - decimal f2 = EvaluateCompiled(f, variable, x2); - logs.Add($"[Adım {i,2}] {variable} = {x2.ToString("0.############", CultureInfo.InvariantCulture),-18} | f({variable}) = {f2.ToString("E3", CultureInfo.InvariantCulture),-11} | |Δ| = {err.ToString("E3", CultureInfo.InvariantCulture)}"); - - if (err <= tol || DecimalMath.Abs(f2) <= tol) - { - logs.Add($"✓ Yakınsama {i}. adımda tamamlandı."); - break; - } - } - - decimal finalFx = EvaluateCompiled(f, variable, x2); - logs.Add(""); - logs.Add($">>> BULUNAN KÖK: {variable} = {x2.ToString("0.##########", CultureInfo.InvariantCulture)} (f({variable}) = {finalFx.ToString("0.##########", CultureInfo.InvariantCulture)})"); - return logs; - } - - public static List Method_RegulaFalsi(string _eq, decimal _min, decimal _max, int _iterationCount, string variable = "x") - { - if (string.IsNullOrWhiteSpace(variable)) variable = "x"; - Function f = CompileFunction(_eq); - List logs = new List(); - - decimal a = _min; - decimal b = _max; - if (a >= b) - { - return new List { "Hata: Alt sınır (Min) üst sınırdan (Max) küçük olmalıdır." }; - } - - decimal fa = EvaluateCompiled(f, variable, a); - decimal fb = EvaluateCompiled(f, variable, b); - - if (DecimalMath.Abs(fa) <= 1e-12m) - { - logs.Add($"✓ Alt sınır {variable} = {a} zaten bir köktür: f({a}) = {fa}"); - logs.Add($">>> BULUNAN KÖK: {variable} = {a.ToString("0.##########", CultureInfo.InvariantCulture)} (f({variable}) = 0)"); - return logs; - } - if (DecimalMath.Abs(fb) <= 1e-12m) - { - logs.Add($"✓ Üst sınır {variable} = {b} zaten bir köktür: f({b}) = {fb}"); - logs.Add($">>> BULUNAN KÖK: {variable} = {b.ToString("0.##########", CultureInfo.InvariantCulture)} (f({variable}) = 0)"); - return logs; - } - - if (fa * fb > 0) - { - return new List - { - $"Uyarı: Seçilen [{a}, {b}] aralığında işaret değişimi yok!", - $"f({a}) = {fa:0.######} ve f({b}) = {fb:0.######} aynı işaretli.", - "Regula Falsi yöntemi için f(Min) * f(Max) <= 0 olmalıdır." - }; - } - - logs.Add($"--- Regula Falsi (Yer Değiştirme) Yöntemi [{a}, {b}] ---"); - decimal c = a; - decimal tol = 1e-11m; - int side = 0; - - for (int i = 1; i <= _iterationCount; i++) - { - if (DecimalMath.Abs(fb - fa) <= 1e-15m) break; - - decimal prevC = c; - c = (a * fb - b * fa) / (fb - fa); - decimal fc = EvaluateCompiled(f, variable, c); - decimal err = DecimalMath.Abs(c - prevC); - - logs.Add($"[Adım {i,2}] {variable} = {c.ToString("0.############", CultureInfo.InvariantCulture),-18} | f({variable}) = {fc.ToString("E3", CultureInfo.InvariantCulture),-11} | |Δ| = {err.ToString("E3", CultureInfo.InvariantCulture)}"); - - if (DecimalMath.Abs(fc) <= tol || (i > 1 && err <= tol)) - { - logs.Add($"✓ Yakınsama {i}. adımda tamamlandı."); - break; - } - - if (fa * fc <= 0) - { - b = c; - fb = fc; - if (side == -1) fa *= 0.5m; - side = -1; - } - else - { - a = c; - fa = fc; - if (side == 1) fb *= 0.5m; - side = 1; - } - } - - decimal finalFx = EvaluateCompiled(f, variable, c); - logs.Add(""); - logs.Add($">>> BULUNAN KÖK: {variable} = {c.ToString("0.##########", CultureInfo.InvariantCulture)} (f({variable}) = {finalFx.ToString("0.##########", CultureInfo.InvariantCulture)})"); - return logs; - } -} diff --git a/tests/ttCalculator.Tests/Program.cs b/tests/ttCalculator.Tests/Program.cs index c61f58e..65f172b 100644 --- a/tests/ttCalculator.Tests/Program.cs +++ b/tests/ttCalculator.Tests/Program.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; using DotNetMatrix; @@ -9,25 +9,166 @@ namespace MathApp.Tests { static void Main(string[] args) { - Console.WriteLine("DEBUG SOLVER STARTED"); + Console.WriteLine("========================================"); + Console.WriteLine("ttCalculator v2.3 Algorithm Verification"); + Console.WriteLine("========================================"); + + int passed = 0; + int total = 0; + + void AssertTrue(bool condition, string testName) + { + total++; + if (condition) + { + passed++; + Console.WriteLine($"[PASS] {testName}"); + } + else + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"[FAIL] {testName}"); + Console.ResetColor(); + } + } + + // Test 1: Linear system solver try { List eqs = new List { "x+y-3", "x-y-1" }; Dictionary init = new Dictionary { { "x", 0 }, { "y", 0 } }; - - Console.WriteLine("Calling SolveEquationSystem..."); var res = NumericalMethods.MethodMultiVar_SolveEquationSystem(eqs, init, 2, 0.001m); - - Console.WriteLine("Result count: " + (res == null ? "NULL" : res.Count.ToString())); - if(res != null) - { - foreach(var kv in res) Console.WriteLine(kv.Key + "=" + kv.Value); - } + AssertTrue(res != null && Math.Abs((double)res["x"] - 2.0) < 1e-4 && Math.Abs((double)res["y"] - 1.0) < 1e-4, "Equation System Solver (2x2)"); } - catch(Exception ex) + catch (Exception ex) { - Console.WriteLine("EXCEPTION CAUGHT: " + ex.ToString()); + AssertTrue(false, "Equation System Solver: " + ex.Message); } + + // Test 2: Continued Fractions (ToFraction) + try + { + var f1 = NumericalMethods.ToFraction(1m / 6m); + AssertTrue(f1.HasValue && f1.Value.Num == 1 && f1.Value.Denom == 6, "ToFraction(1/6) == 1/6"); + + var f2 = NumericalMethods.ToFraction(1m / 120m); + AssertTrue(f2.HasValue && f2.Value.Num == 1 && f2.Value.Denom == 120, "ToFraction(1/120) == 1/120"); + + var f3 = NumericalMethods.ToFraction(0.75m); + AssertTrue(f3.HasValue && f3.Value.Num == 3 && f3.Value.Denom == 4, "ToFraction(0.75) == 3/4"); + } + catch (Exception ex) + { + AssertTrue(false, "ToFraction: " + ex.Message); + } + + // Test 3: Multi-root interval scanning + try + { + // sin(x) = 0 in [-3.5, 3.5] has roots at -pi, 0, pi + var roots = NumericalMethods.FindAllRoots("sin(x)", -3.5m, 3.5m, "x"); + AssertTrue(roots.Count >= 3, $"FindAllRoots for sin(x) found {roots.Count} roots (expected >= 3)"); + } + catch (Exception ex) + { + AssertTrue(false, "FindAllRoots: " + ex.Message); + } + + // Test 4: Single ODE (y' = y, y(0) = 1 => y(1) = e ≈ 2.71828) + try + { + var eulerRes = DifferentialEquations.SolveOde("y", 0m, 1m, 1m, 100, "Euler"); + decimal yEuler = eulerRes[eulerRes.Count - 1].Y; + AssertTrue(Math.Abs((double)yEuler - Math.E) < 0.05, $"ODE Euler y(1) = {yEuler:F4} (expected ≈ e)"); + + var rk4Res = DifferentialEquations.SolveOde("y", 0m, 1m, 1m, 100, "RK4"); + decimal yRk4 = rk4Res[rk4Res.Count - 1].Y; + AssertTrue(Math.Abs((double)yRk4 - Math.E) < 1e-4, $"ODE RK4 y(1) = {yRk4:F6} (expected ≈ e)"); + + var rk8Res = DifferentialEquations.SolveOde("y", 0m, 1m, 1m, 100, "RK8"); + decimal yRk8 = rk8Res[rk8Res.Count - 1].Y; + AssertTrue(Math.Abs((double)yRk8 - Math.E) < 1e-5, $"ODE RK8 y(1) = {yRk8:F8} (expected ≈ e)"); + } + catch (Exception ex) + { + AssertTrue(false, "SolveOde: " + ex.Message); + } + + // Test 5: ODE System (Harmonic Oscillator: y1' = y2, y2' = -y1 with y1(0)=1, y2(0)=0) + // Exact solution: y1(t) = cos(t), y2(t) = -sin(t) + // At t = 2*pi, y1 ≈ 1.0, y2 ≈ 0.0 + try + { + List sysEqs = new List { "y2", "-y1" }; + List vars = new List { "y1", "y2" }; + Dictionary inits = new Dictionary { { "y1", 1m }, { "y2", 0m } }; + decimal tEnd = (decimal)(2.0 * Math.PI); + + var sysRes = DifferentialEquations.SolveOdeSystem(sysEqs, vars, inits, 0m, tEnd, 200, "RK4"); + var last = sysRes[sysRes.Count - 1]; + decimal y1End = last.YValues["y1"]; + decimal y2End = last.YValues["y2"]; + AssertTrue(Math.Abs((double)y1End - 1.0) < 1e-3 && Math.Abs((double)y2End) < 1e-3, + $"ODE System RK4 Harmonic Oscillator y1={y1End:F5}, y2={y2End:F5} (expected ~1, ~0)"); + } + catch (Exception ex) + { + AssertTrue(false, "SolveOdeSystem: " + ex.Message); + } + + // Test 6: 1D Heat Equation (u_t = alpha * u_xx) + // With u(x,0) = sin(pi*x), exact solution decays as exp(-alpha*pi^2*t)*sin(pi*x) + try + { + var pdeHeat = DifferentialEquations.Solve1DPde( + DifferentialEquations.PdeType.HeatEquation, + "sin(pi * x)", + 1.0m, + 0.2m, + 21, + 100, + 0.1m, + 0m, + 0m + ); + decimal midU = pdeHeat.U[10, 99]; // x = 0.5 at final time + double expected = Math.Exp(-0.1 * Math.PI * Math.PI * 0.2) * Math.Sin(Math.PI * 0.5); + AssertTrue(Math.Abs((double)midU - expected) < 0.02, + $"1D Heat FTCS mid-point U={midU:F4} (expected ≈ {expected:F4})"); + } + catch (Exception ex) + { + AssertTrue(false, "Solve1DPde Heat: " + ex.Message); + } + + // Test 7: Coupled Reaction-Diffusion PDE System + try + { + var coupledPde = DifferentialEquations.SolveCoupledPdeSystem( + "-u * v^2 + 0.04 * (1 - u)", + "u * v^2 - 0.09 * v", + "1 - 0.5 * exp(-100 * (x - 0.5)^2)", + "0.25 * exp(-100 * (x - 0.5)^2)", + 1.0m, + 0.5m, + 21, + 100, + 0.001m, + 0.0005m + ); + AssertTrue(coupledPde.U != null && coupledPde.V != null && coupledPde.U[10, 99] > 0m, + "Coupled PDE System (Gray-Scott Reaction-Diffusion)"); + } + catch (Exception ex) + { + AssertTrue(false, "SolveCoupledPdeSystem: " + ex.Message); + } + + Console.WriteLine("========================================"); + Console.WriteLine($"RESULTS: {passed}/{total} tests passed ({(passed * 100.0 / total):F1}%)"); + Console.WriteLine("========================================"); + + if (passed != total) Environment.Exit(1); } } } diff --git a/tests/ttCalculator.Tests/QRDecomposition.cs b/tests/ttCalculator.Tests/QRDecomposition.cs deleted file mode 100644 index 8702b0f..0000000 --- a/tests/ttCalculator.Tests/QRDecomposition.cs +++ /dev/null @@ -1,287 +0,0 @@ -using System; -using System.Runtime.Serialization; - -namespace DotNetMatrix -{ - - /// QR Decomposition. - /// For an m-by-n matrix A with m >= n, the QR decomposition is an m-by-n - /// orthogonal matrix Q and an n-by-n upper triangular matrix R so that - /// A = Q*R. - /// - /// The QR decompostion always exists, even if the matrix does not have - /// full rank, so the constructor will never fail. The primary use of the - /// QR decomposition is in the least squares solution of nonsquare systems - /// of simultaneous linear equations. This will fail if IsFullRank() - /// returns false. - /// - - [Serializable] - public class QRDecomposition : System.Runtime.Serialization.ISerializable - { - #region Class variables - - /// Array for internal storage of decomposition. - /// @serial internal array storage. - /// - private decimal[][] QR; - - /// Row and column dimensions. - /// @serial column dimension. - /// @serial row dimension. - /// - private int m, n; - - /// Array for internal storage of diagonal of R. - /// @serial diagonal of R. - /// - private decimal[] Rdiag; - - #endregion // Class variables - - #region Constructor - - /// QR Decomposition, computed by Householder reflections. - /// Rectangular matrix - /// - /// Structure to access R and the Householder vectors and compute Q. - /// - - public QRDecomposition(GeneralMatrix A) - { - // Initialize. - QR = A.ArrayCopy; - m = A.RowDimension; - n = A.ColumnDimension; - Rdiag = new decimal[n]; - - // Main loop. - for (int k = 0; k < n; k++) - { - // Compute 2-norm of k-th column without under/overflow. - decimal nrm = 0; - for (int i = k; i < m; i++) - { - nrm = Maths.Hypot(nrm, QR[i][k]); - } - - if (nrm != 0.0m) - { - // Form k-th Householder vector. - if (QR[k][k] < 0) - { - nrm = - nrm; - } - for (int i = k; i < m; i++) - { - QR[i][k] /= nrm; - } - QR[k][k] += 1.0m; - - // Apply transformation to remaining columns. - for (int j = k + 1; j < n; j++) - { - decimal s = 0.0m; - for (int i = k; i < m; i++) - { - s += QR[i][k] * QR[i][j]; - } - s = (- s) / QR[k][k]; - for (int i = k; i < m; i++) - { - QR[i][j] += s * QR[i][k]; - } - } - } - Rdiag[k] = - nrm; - } - } - - #endregion // Constructor - - #region Public Properties - - /// Is the matrix full rank? - /// true if R, and hence A, has full rank. - /// - virtual public bool FullRank - { - get - { - for (int j = 0; j < n; j++) - { - if (Rdiag[j] == 0) - return false; - } - return true; - } - } - - /// Return the Householder vectors - /// Lower trapezoidal matrix whose columns define the reflections - /// - virtual public GeneralMatrix H - { - get - { - GeneralMatrix X = new GeneralMatrix(m, n); - decimal[][] H = X.Array; - for (int i = 0; i < m; i++) - { - for (int j = 0; j < n; j++) - { - if (i >= j) - { - H[i][j] = QR[i][j]; - } - else - { - H[i][j] = 0.0m; - } - } - } - return X; - } - - } - - /// Return the upper triangular factor - /// R - /// - virtual public GeneralMatrix R - { - get - { - GeneralMatrix X = new GeneralMatrix(n, n); - decimal[][] R = X.Array; - for (int i = 0; i < n; i++) - { - for (int j = 0; j < n; j++) - { - if (i < j) - { - R[i][j] = QR[i][j]; - } - else if (i == j) - { - R[i][j] = Rdiag[i]; - } - else - { - R[i][j] = 0.0m; - } - } - } - return X; - } - } - - /// Generate and return the (economy-sized) orthogonal factor - /// Q - /// - virtual public GeneralMatrix Q - { - get - { - GeneralMatrix X = new GeneralMatrix(m, n); - decimal[][] Q = X.Array; - for (int k = n - 1; k >= 0; k--) - { - for (int i = 0; i < m; i++) - { - Q[i][k] = 0.0m; - } - Q[k][k] = 1.0m; - for (int j = k; j < n; j++) - { - if (QR[k][k] != 0) - { - decimal s = 0.0m; - for (int i = k; i < m; i++) - { - s += QR[i][k] * Q[i][j]; - } - s = (- s) / QR[k][k]; - for (int i = k; i < m; i++) - { - Q[i][j] += s * QR[i][k]; - } - } - } - } - return X; - } - } - #endregion // Public Properties - - #region Public Methods - - /// Least squares solution of A*X = B - /// A Matrix with as many rows as A and any number of columns. - /// - /// X that minimizes the two norm of Q*R*X-B. - /// - /// Matrix row dimensions must agree. - /// - /// Matrix is rank deficient. - /// - - public virtual GeneralMatrix Solve(GeneralMatrix B) - { - if (B.RowDimension != m) - { - throw new System.ArgumentException("GeneralMatrix row dimensions must agree."); - } - if (!this.FullRank) - { - throw new System.SystemException("Matrix is rank deficient."); - } - - // Copy right hand side - int nx = B.ColumnDimension; - decimal[][] X = B.ArrayCopy; - - // Compute Y = transpose(Q)*B - for (int k = 0; k < n; k++) - { - for (int j = 0; j < nx; j++) - { - decimal s = 0.0m; - for (int i = k; i < m; i++) - { - s += QR[i][k] * X[i][j]; - } - s = (- s) / QR[k][k]; - for (int i = k; i < m; i++) - { - X[i][j] += s * QR[i][k]; - } - } - } - // Solve R*X = Y; - for (int k = n - 1; k >= 0; k--) - { - for (int j = 0; j < nx; j++) - { - X[k][j] /= Rdiag[k]; - } - for (int i = 0; i < k; i++) - { - for (int j = 0; j < nx; j++) - { - X[i][j] -= X[k][j] * QR[i][k]; - } - } - } - - return (new GeneralMatrix(X, n, nx).GetMatrix(0, n - 1, 0, nx - 1)); - } - - #endregion // Public Methods - - // A method called when serializing this class. - void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) - { - } - } -} diff --git a/tests/ttCalculator.Tests/SingularValueDecomposition.cs b/tests/ttCalculator.Tests/SingularValueDecomposition.cs deleted file mode 100644 index 206d5f6..0000000 --- a/tests/ttCalculator.Tests/SingularValueDecomposition.cs +++ /dev/null @@ -1,524 +0,0 @@ -using System; -using System.Runtime.Serialization; - -namespace DotNetMatrix -{ - [Serializable] - public class SingularValueDecomposition : System.Runtime.Serialization.ISerializable - { - private decimal[][] U, V; - private decimal[] s; - private int m, n; - - public SingularValueDecomposition(GeneralMatrix Arg) - { - m = Arg.RowDimension; - n = Arg.ColumnDimension; - - if (m < n) - { - SingularValueDecomposition svdTrans = new SingularValueDecomposition(Arg.Transpose()); - s = (decimal[])svdTrans.s.Clone(); - U = svdTrans.V; - V = svdTrans.U; - return; - } - - decimal[][] A = Arg.ArrayCopy; - int nu = System.Math.Min(m, n); - s = new decimal[System.Math.Min(m + 1, n)]; - U = new decimal[m][]; - for (int i = 0; i < m; i++) - { - U[i] = new decimal[nu]; - } - V = new decimal[n][]; - for (int i2 = 0; i2 < n; i2++) - { - V[i2] = new decimal[n]; - } - decimal[] e = new decimal[n]; - decimal[] work = new decimal[m]; - bool wantu = true; - bool wantv = true; - - int nct = System.Math.Min(m - 1, n); - int nrt = System.Math.Max(0, System.Math.Min(n - 2, m)); - for (int k = 0; k < System.Math.Max(nct, nrt); k++) - { - if (k < nct) - { - s[k] = 0; - for (int i = k; i < m; i++) - { - s[k] = Maths.Hypot(s[k], A[i][k]); - } - if (s[k] != 0.0m) - { - if (A[k][k] < 0.0m) - { - s[k] = - s[k]; - } - for (int i = k; i < m; i++) - { - A[i][k] /= s[k]; - } - A[k][k] += 1.0m; - } - s[k] = - s[k]; - } - for (int j = k + 1; j < n; j++) - { - if ((k < nct) & (s[k] != 0.0m)) - { - decimal t = 0; - for (int i = k; i < m; i++) - { - t += A[i][k] * A[i][j]; - } - t = (- t) / A[k][k]; - for (int i = k; i < m; i++) - { - A[i][j] += t * A[i][k]; - } - } - e[j] = A[k][j]; - } - if (wantu & (k < nct)) - { - for (int i = k; i < m; i++) - { - U[i][k] = A[i][k]; - } - } - if (k < nrt) - { - e[k] = 0; - for (int i = k + 1; i < n; i++) - { - e[k] = Maths.Hypot(e[k], e[i]); - } - if (e[k] != 0.0m) - { - if (e[k + 1] < 0.0m) - { - e[k] = - e[k]; - } - for (int i = k + 1; i < n; i++) - { - e[i] /= e[k]; - } - e[k + 1] += 1.0m; - } - e[k] = - e[k]; - if ((k + 1 < m) & (e[k] != 0.0m)) - { - for (int i = k + 1; i < m; i++) - { - work[i] = 0.0m; - } - for (int j = k + 1; j < n; j++) - { - for (int i = k + 1; i < m; i++) - { - work[i] += e[j] * A[i][j]; - } - } - for (int j = k + 1; j < n; j++) - { - decimal t = (- e[j]) / e[k + 1]; - for (int i = k + 1; i < m; i++) - { - A[i][j] += t * work[i]; - } - } - } - if (wantv) - { - for (int i = k + 1; i < n; i++) - { - V[i][k] = e[i]; - } - } - } - } - - int p = System.Math.Min(n, m + 1); - if (nct < n) - { - s[nct] = A[nct][nct]; - } - if (m < p) - { - s[p - 1] = 0.0m; - } - if (nrt + 1 < p) - { - e[nrt] = A[nrt][p - 1]; - } - e[p - 1] = 0.0m; - - if (wantu) - { - for (int j = nct; j < nu; j++) - { - for (int i = 0; i < m; i++) - { - U[i][j] = 0.0m; - } - U[j][j] = 1.0m; - } - for (int k = nct - 1; k >= 0; k--) - { - if (s[k] != 0.0m) - { - for (int j = k + 1; j < nu; j++) - { - decimal t = 0; - for (int i = k; i < m; i++) - { - t += U[i][k] * U[i][j]; - } - t = (- t) / U[k][k]; - for (int i = k; i < m; i++) - { - U[i][j] += t * U[i][k]; - } - } - for (int i = k; i < m; i++) - { - U[i][k] = - U[i][k]; - } - U[k][k] = 1.0m + U[k][k]; - for (int i = 0; i < k - 1; i++) - { - U[i][k] = 0.0m; - } - } - else - { - for (int i = 0; i < m; i++) - { - U[i][k] = 0.0m; - } - U[k][k] = 1.0m; - } - } - } - - if (wantv) - { - for (int k = n - 1; k >= 0; k--) - { - if ((k < nrt) & (e[k] != 0.0m)) - { - for (int j = k + 1; j < nu; j++) - { - decimal t = 0; - for (int i = k + 1; i < n; i++) - { - t += V[i][k] * V[i][j]; - } - t = (- t) / V[k + 1][k]; - for (int i = k + 1; i < n; i++) - { - V[i][j] += t * V[i][k]; - } - } - } - for (int i = 0; i < n; i++) - { - V[i][k] = 0.0m; - } - V[k][k] = 1.0m; - } - } - - int pp = p - 1; - int iter = 0; - decimal eps = DecimalMath.Pow(2.0m, -64.0m); - while (p > 0 && iter < 150) - { - int k, kase; - for (k = p - 2; k >= - 1; k--) - { - if (k == - 1) - { - break; - } - if (System.Math.Abs(e[k]) <= eps * (System.Math.Abs(s[k]) + System.Math.Abs(s[k + 1]))) - { - e[k] = 0.0m; - break; - } - } - if (k == p - 2) - { - kase = 4; - } - else - { - int ks; - for (ks = p - 1; ks >= k; ks--) - { - if (ks == k) - { - break; - } - decimal t = (ks != p?System.Math.Abs(e[ks]):0.0m) + (ks != k + 1?System.Math.Abs(e[ks - 1]):0.0m); - if (System.Math.Abs(s[ks]) <= eps * t) - { - s[ks] = 0.0m; - break; - } - } - if (ks == k) - { - kase = 3; - } - else if (ks == p - 1) - { - kase = 1; - } - else - { - kase = 2; - k = ks; - } - } - k++; - - switch (kase) - { - case 1: - { - decimal f = e[p - 2]; - e[p - 2] = 0.0m; - for (int j = p - 2; j >= k; j--) - { - decimal t = Maths.Hypot(s[j], f); - decimal cs = s[j] / t; - decimal sn = f / t; - s[j] = t; - if (j != k) - { - f = (- sn) * e[j - 1]; - e[j - 1] = cs * e[j - 1]; - } - if (wantv) - { - for (int i = 0; i < n; i++) - { - t = cs * V[i][j] + sn * V[i][p - 1]; - V[i][p - 1] = (- sn) * V[i][j] + cs * V[i][p - 1]; - V[i][j] = t; - } - } - } - } - break; - case 2: - { - decimal f = e[k - 1]; - e[k - 1] = 0.0m; - for (int j = k; j < p; j++) - { - decimal t = Maths.Hypot(s[j], f); - decimal cs = s[j] / t; - decimal sn = f / t; - s[j] = t; - f = (- sn) * e[j]; - e[j] = cs * e[j]; - if (wantu) - { - for (int i = 0; i < m; i++) - { - t = cs * U[i][j] + sn * U[i][k - 1]; - U[i][k - 1] = (- sn) * U[i][j] + cs * U[i][k - 1]; - U[i][j] = t; - } - } - } - } - break; - case 3: - { - decimal scale = System.Math.Max(System.Math.Max(System.Math.Max(System.Math.Max(System.Math.Abs(s[p - 1]), System.Math.Abs(s[p - 2])), System.Math.Abs(e[p - 2])), System.Math.Abs(s[k])), System.Math.Abs(e[k])); - decimal sp = s[p - 1] / scale; - decimal spm1 = s[p - 2] / scale; - decimal epm1 = e[p - 2] / scale; - decimal sk = s[k] / scale; - decimal ek = e[k] / scale; - decimal b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2.0m; - decimal c = (sp * epm1) * (sp * epm1); - decimal shift = 0.0m; - if ((b != 0.0m) | (c != 0.0m)) - { - shift = (decimal)DecimalMath.Sqrt(b * b + c); - if (b < 0.0m) - { - shift = - shift; - } - shift = c / (b + shift); - } - decimal f = (sk + sp) * (sk - sp) + shift; - decimal g = sk * ek; - - for (int j = k; j < p - 1; j++) - { - decimal t = Maths.Hypot(f, g); - decimal cs = f / t; - decimal sn = g / t; - if (j != k) - { - e[j - 1] = t; - } - f = cs * s[j] + sn * e[j]; - e[j] = cs * e[j] - sn * s[j]; - g = sn * s[j + 1]; - s[j + 1] = cs * s[j + 1]; - if (wantv) - { - for (int i = 0; i < n; i++) - { - t = cs * V[i][j] + sn * V[i][j + 1]; - V[i][j + 1] = (- sn) * V[i][j] + cs * V[i][j + 1]; - V[i][j] = t; - } - } - t = Maths.Hypot(f, g); - cs = f / t; - sn = g / t; - s[j] = t; - f = cs * e[j] + sn * s[j + 1]; - s[j + 1] = (- sn) * e[j] + cs * s[j + 1]; - g = sn * e[j + 1]; - e[j + 1] = cs * e[j + 1]; - if (wantu && (j < m - 1)) - { - for (int i = 0; i < m; i++) - { - t = cs * U[i][j] + sn * U[i][j + 1]; - U[i][j + 1] = (- sn) * U[i][j] + cs * U[i][j + 1]; - U[i][j] = t; - } - } - } - e[p - 2] = f; - iter = iter + 1; - } - break; - case 4: - { - if (s[k] <= 0.0m) - { - s[k] = (s[k] < 0.0m?- s[k]:0.0m); - if (wantv) - { - for (int i = 0; i <= pp; i++) - { - V[i][k] = - V[i][k]; - } - } - } - while (k < pp) - { - if (s[k] >= s[k + 1]) - { - break; - } - decimal t = s[k]; - s[k] = s[k + 1]; - s[k + 1] = t; - if (wantv && (k < n - 1)) - { - for (int i = 0; i < n; i++) - { - t = V[i][k + 1]; V[i][k + 1] = V[i][k]; V[i][k] = t; - } - } - if (wantu && (k < m - 1)) - { - for (int i = 0; i < m; i++) - { - t = U[i][k + 1]; U[i][k + 1] = U[i][k]; U[i][k] = t; - } - } - k++; - } - iter = 0; - p--; - } - break; - } - } - } - - virtual public decimal[] SingularValues - { - get - { - return s; - } - } - - virtual public GeneralMatrix S - { - get - { - int nu = System.Math.Min(m, n); - GeneralMatrix X = new GeneralMatrix(nu, nu); - decimal[][] S = X.Array; - for (int i = 0; i < nu; i++) - { - for (int j = 0; j < nu; j++) - { - S[i][j] = 0.0m; - } - S[i][i] = this.s[i]; - } - return X; - } - } - - public virtual GeneralMatrix GetU() - { - return new GeneralMatrix(U, m, System.Math.Min(m, n)); - } - - public virtual GeneralMatrix GetV() - { - return new GeneralMatrix(V, n, System.Math.Min(m, n)); - } - - public virtual decimal Norm2() - { - return s[0]; - } - - public virtual decimal Condition() - { - decimal minS = s[System.Math.Min(m, n) - 1]; - return minS != 0m ? s[0] / minS : decimal.MaxValue; - } - - public virtual int Rank() - { - decimal eps = (decimal)System.Math.Pow(2.0f, - 52.0f); - decimal tol = System.Math.Max(m, n) * s[0] * eps; - int r = 0; - for (int i = 0; i < s.Length; i++) - { - if (s[i] > tol) - { - r++; - } - } - return r; - } - - void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) - { - } - } -} diff --git a/tests/ttCalculator.Tests/ttCalculator.Tests.csproj b/tests/ttCalculator.Tests/ttCalculator.Tests.csproj index c1368a7..6a86e01 100644 --- a/tests/ttCalculator.Tests/ttCalculator.Tests.csproj +++ b/tests/ttCalculator.Tests/ttCalculator.Tests.csproj @@ -2,9 +2,14 @@ Exe - net8.0 + net8.0-windows + true enable disable + + + +