Files
kunlun/dtest/ada_test/math.c
2024-09-28 14:24:04 +08:00

122 lines
2.0 KiB
C

#include "math.h"
float iot_abs(float x)
{
if(x<0) x=0-x;
return x;
}
float iot_sin(float x)
{
const float B = 1.2732395447;
const float C = -0.4052847346;
const float P = 0.2310792853;//0.225;
float y = B * x + C * x * iot_abs(x);
y = P * (y * iot_abs(y) - y) + y;
return y;
}
float iot_cos(float x)
{
const float Q = 1.5707963268;
const float PI =3.1415926536;
x += Q;
if(x > PI)
x -= 2 * PI;
return( iot_sin(x));
}
float iot_sqrt(float a)
{
double x,y;
x=0.0;
y=a/2;
while(x!=y)
{
x=y;
y=(x+a/x)/2;
}
return x;
}
float iot_pow(float a,int b)
{
float r=a;
if(b>0)
{
while(--b)
r*=a;
}
else if(b<0)
{
while(++b)
r*=a;
r=1.0/r;
}
else r=0;
return r;
}
static double Sqrt(double x)
{
if (x < 0)
return -1;
if (x == 0)
return 0;
double y = (double)iot_sqrt((double)x);
return (y + x / y) / 2;
}
static double NegativeLog(double q)
{
int p;
double pi2 = 6.283185307179586476925286766559;
double eps2 = 0.00000000000001; // 1e-14
double eps1; // 1e-28
double r = q, s = q, n = q, q2 = q * q, q1 = q2 * q;
eps1 = eps2 * eps2;
for (p = 1; (n *= q1) > eps1; s += n, q1 *= q2)
r += (p = !p) ? n : -n;
double u = 1 - 2 * r, v = 1 + 2 * s, t = u / v;
double a = 1, b = Sqrt(1 - t * t * t * t);
for (; a - b > eps2; b = Sqrt(a * b), a = t)
t = (a + b) / 2;
return pi2 / (a + b) / v / v;
}
static double Log(double x)
{
int k = 0;
double ln10 = 2.30258509299404568401799145468;
if (x <= 0)
return -1;
if (x == 1)
return 0;
for (; x > 0.1; k++)
x /= 10;
for (; x <= 0.01; k--)
x *= 10;
return k * ln10 - NegativeLog(x);
}
double Log10(double x)
{
double ln10 = 2.30258509299404568401799145468;
return Log(x) / ln10;
}