目前来看,以下算法开2次方能在百分之2以内的精度,开3次方能在百分之6以内的精度,而且误差主要出在20以内。200以上则是千分位误差
`
using System;
using System.Collections.Generic; using System.Linq; using System.Text;
namespace KaiFangTest { class Program { static void Main(string[] args) { for (int i = 4; i <= 100000; i++) { float i2 = get2(i); //i2 = (float)Math.Truncate((double)i210)/10; //i2 = (i2 + i / i2 ) / 2; float wuCha = Math.Abs(((i2 * i2) - i) / i); if (Math.Abs(wuCha) > 0.01) System.Console.WriteLine(i.ToString() + " " + i2.ToString("N2") + " " + (wuCha).ToString("N4")); } System.Console.WriteLine("*******"); for (int i = 8; i <= 10000; i++) { float i3 = get3(i); //i3 = (float)Math.Truncate((double)i310)/10; //i3 = (2 * i3 + i / i3 / i3) / 3; float wuCha = Math.Abs((( i3 i3 * i3) - i) / i); if (wuCha > 0.1) System.Console.WriteLine(i.ToString() + " " + i3.ToString("N3") + " " + (wuCha).ToString("N4")); }
//for (int i = 2; i < 100; i++)
// System.Console.WriteLine(i.ToString() + " " + find2(i));
}
static float get2(int t)
{
float a = find2(t);
return (a + t / a) / 2;
}
static float find2(int t)
{
for (int i = 0; i < t; i++)
if (i * i == t)
return i;
else
if (i * i > t)
{
int small = i - 1;
int result =i;
if ( (result * result - t) != Math.Min(result * result - t, t - small * small))
result = small;
float misus = (i * i - t) / (t - small * small );
if (misus > 0.5 && misus < 2)
return (float)(small + 0.5);
return result;
}
return 0;
}
static float get3(float t)
{
float a = find3(t);
return (a*2 + t / a/a) / 3;
}
static float find3(float t)
{
for (int i = 0; i < t; i++)
if (i * i*i == t)
return i;
else if (i * i*i > t)
{
int small = i - 1;
int result = i;
if ((result * result * result - t) != Math.Min(result * result * result - t, t - small* small * small))
result = small;
float misus = (i*i*i-t)/(t - small* small * small);
if (misus > 0.3 && misus < 3)
return (float)(small + 0.5);
return result;
}
return 0;
}
}
} `