C# :: Aufgabe #183 :: Lösung #1
4 Lösungen
#183
Funktion um Pi zu berechnen.
Anfänger - C#
von Felix
- 09.07.2017 um 21:59 Uhr
Schreibe eine Methode um Pi zu berechnen. Versuche Pi auf so viele Stellen wie möglich zu berechnen.
#1
von hollst (13980 Punkte)
- 12.07.2017 um 16:41 Uhr
using System;
using static System.Console;
using System.Numerics; //muss zu Verweisen hinzugefügt werden
using System.Diagnostics;
namespace pi_183{
class Program {
static string NL = Environment.NewLine, LZ = " ";
static void Main() {
Stopwatch sw = new Stopwatch();
sw.Start();
int genauigkeit = 1001;
WriteLine("Garantierte Genauigkeit: " + (genauigkeit - 1).ToString("n0") + " Nachkommastellen" + NL);
int n = 10;
BigInteger pi1 = 0, pi2 = 0;
bool bo_ok = false;
while (!bo_ok) {
pi1 = pi2;
rational L2 = new rational();
L2 = Lambert(1, n + 1);
BigInteger p2 = BigInteger.Pow(10, L2.zaehler.ToString().Length);
pi2 = p2 * 4 * L2.nenner / L2.zaehler;
int identisch = pi2.identisch_bis(pi1);
bo_ok = genauigkeit <= identisch;
n++;
}
WriteLine(pi2.ToString().MitCharAnzahl(genauigkeit));
WriteLine(NL + Math.PI * Math.Pow(10, 14));
sw.Stop();
TimeSpan ts = sw.Elapsed;
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
WriteLine(NL + "Rechenzeit " + elapsedTime);
ReadKey();
}
#region biginteger region
public struct rational
{
public BigInteger zaehler;
public BigInteger nenner;
}
public static rational div(rational z1, rational z2) {
rational erg;
erg.zaehler = z1.zaehler * z2.nenner;
erg.nenner = z1.nenner * z2.zaehler;
return erg;
}
public static rational add(rational z1, rational z2) {
rational erg;
erg.nenner = z1.nenner * z2.nenner;
erg.zaehler = z1.zaehler * z2.nenner + z2.zaehler * z1.nenner;
return erg;
}
public static rational Lambert(int k, int n) { // nach Lamberts Kettenbruch
// lambert(k) = 2 * k - 1 + k * k / lambert(k + 1)
rational erg;
if (k == n)
{
erg.zaehler = 1;
erg.nenner = 1;
return erg;
}
rational a, b;
a.zaehler = 2 * k - 1; a.nenner = 1;
b.zaehler = k * k; b.nenner = 1;
erg = add(a, div(b, Lambert(k + 1, n)));
return erg;
}
#endregion
}
public static class MyExtensions {
public static string MitCharAnzahl(this string s, int chars) {
string result = string.Empty;
for (var i = 0; i < s.Length; i++)
if (i < chars)
result += s[i].ToString();
else
break;
return result;
}
public static int identisch_bis(this BigInteger z1, BigInteger z2)
{
int result = 0;
char[] c1 = z1.ToString().ToCharArray();
char[] c2 = z2.ToString().ToCharArray();
for (var i = 0; i < Math.Min(c1.Length, c2.Length); i++)
if (c1[i] == c2[i])
result++;
else
break;
return result;
}
}
}
Kommentare:
Für diese Lösung gibt es noch keinen Kommentar
Seite 1 von 0
1
