zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C# 常用算法 迭代

2023-09-11 14:16:46 时间

一 迭代

逻辑上:多次使用同一算法;
形式上:a=f(a);
示例:求平方根;
倍边法求Pi;
其他,如:数字平方和、Mandelbrot集,Jullia集;

求平方根

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 求平方根
{
    public class Sqrt
    {
        public static void Main(string[] args)
        {
            Console.WriteLine(sqrt(98));
            Console.WriteLine(Math.Sqrt(2.0));
            Console.ReadKey();
        }

        static double sqrt(double a)
        {
            double x = 1.0;
            do
            {
                Console.WriteLine(x + "," + a / x);
                x = (x + a / x) / 2;
            } while (Math.Abs(x * x - a) / a > 1e-6);
            return x;
        }
    }
}

倍边法求π

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 倍边法求π
{
    class BeiBianFaQiuπ
    {
        static void Main()
        {
            double a = 1;
            for(int n=0;n<=10;n++)
            {
                a = Math.Sqrt(2 - Math.Sqrt(4 - a * a));
                double pi = a * 3 * Math.Pow(2, n);
                Console.WriteLine(pi);
            }
            Console.WriteLine(Math.PI);
            Console.ReadKey();
        }
    }
}