我在生成高斯数
时遇到了这个问题。问题是这样的:
这是我目前编写的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SirurileLuiGauss
{
class Program
{
static int[] a = new int[100];
static int[] b = new int[100];
static List<int> list_a = new List<int>();
static List<int> list_b = new List<int>();
static int GaussA(int n)
{
if(n <= 0)
{
int a = 0;
list_a.Add(a);
return a;
}
else
{
int a = (GaussA(n - 1) + GaussB(n - 1))/2;
list_a.Add(a);
return a;
}
}
static int GaussB(int n)
{
if(n <= 0)
{
int b = 0;
list_b.Add(b);
return b;
}
else
{
int b = (int) Math.Sqrt(GaussA(n - 1) * GaussB(n - 1));
list_b.Add(b);
return b;
}
}
static void Main(string[] args)
{
int n = 5;
Console.WriteLine("GAUSS_111");
GaussA(n);
foreach (int element in list_a)
{
Console.WriteLine("GAUSS_A = "+element);
}
foreach (int element in list_b)
{
Console.WriteLine("GAUSS_B = " + element);
}
Console.WriteLine("\n\n");
// Clear the list
list_a = new List<int>();
list_b = new List<int>();
Console.WriteLine("GAUSS_222");
GaussB(n);
foreach (int element in list_a)
{
Console.WriteLine("GAUSS_A = " + element);
}
foreach (int element in list_b)
{
Console.WriteLine("GAUSS_B = " + element);
}
Console.Read();
}
}
}
这是完全错误的,给我的输出像 0 0 0 0 ...
- 我做错了什么?
- 我可以在任何地方找到它吗?比如图书馆之类的?
- 我认为这种方法是通过计算
积分
并找出数组的peak/max_number 是什么。然后尝试向后迭代以找到所有数字,直到我们命中a > 0
和b > 0
。主要问题是您必须将 2 个数组 保存到内存中,这很难……我说得对吗? - 如何在
C#
中计算该积分? - 为什么需要
epsilon
来保证精度?
非常感谢。
最佳答案
问题开始于"let a0 = ... b0 = ...";所以你需要a0和b0 作为输入参数。另一个问题是你在这里不需要任何数组或列表 (想象一下,你被要求找出第 百万次 迭代),动态规划 在这里是一个更好的选择:
// I let myselft return the result as Tupple<,>
public static Tuple<Double, Double> Gauss(Double a0, Double b0, int n) {
Double prior_a;
Double prior_b;
Double a = a0;
Double b = b0;
for (int i = 0; i < n; ++i) {
prior_a = a;
prior_b = b;
a = (prior_a + prior_b) / 2.0;
b = Math.Sqrt(prior_a * prior_b);
}
return new Tuple<Double, Double>(a, b);
}
Simple test: let a0 = 1; b0 = 5, so we have
Theory:
itt # a b
0 1 5
1 3 sqrt(5)
2 (3+sqrt(5))/2 sqrt(3*sqrt(5))
Actual:
Gauss(1, 5, 0); // returns (1, 5)
Gauss(1, 5, 1); // -/- (3, 2.23606797749979)
Gauss(1, 5, 2); // -/- (2.61803398874989, 2.59002006411135)
Gauss(1, 5, 3); // -/- (2.60402702643062, 2.60398935469938)
Gauss(1, 5, 10); // -/- (2.60400819053094, 2.60400819053094)
Gauss(1, 5, 100); // -/- (2.60400819053094, 2.60400819053094)
附言您无法计算(例如,获取 double 值)不定 积分,因为它等于 F(x) + C,其中 C 是任意常数;对于定积分,您可以使用 Simpson 算法
关于c# - 生成高斯数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21288948/