creating a floating point power function in c - c

So here's the current implementation of my power function.
pow(x, n) int x, n;
{
int r = 1;
int i;
for (i = 0; i < n; i++)
r *= x;
return (r);
}
The problem is how it only works for whole numbers & doesn't work with floats like pow(4, .5).
Of course, I've already tried changing everything to double & I know how a standard library function exists. Also I've seen Floating point exponentiation without power-function, but none of the solutions were working nor what I wanted.
Here is the version, where I used doubles.
double pow(x, n)
double x, n;
{
double r = 1.;
int i;
for (i = 0; i < n; i++)
r *= x;
return (r);
}
It returns 1., when I use it as pow(4., .5).

Related

Mean function using values from double array displaying wrong values

Very new to C, anyways been coding a program where you enter pairs of doubles which are stored in separate arrays. I have created a function to get the mean of the numbers but when I call it inside main the values are different. Any ideas?
MEAN FUNCTION:
mean(double *arr)
{
double sum = 0.0;
double meanValue = 0.0;
int i;
for (i = 0; i < arr[i]; i++)
{
sum += arr[i];
meanValue = sum / i;
}
printf("\nmean: %.3lf", meanValue);
}
MAIN:
double num1[1001];
mean(num1);
And, I am getting the num1 and num2 values using:
for (k = 0; (scanf_s("%lf,%lf", &num1[k], &num2[k] ) == 2); k++)
The function needs to know how many of the array elements it should process.
mean(double *arr, int size)
{
double sum = 0.0;
double meanValue = 0.0;
int i;
for (i = 0; i < size; i++)
{
sum += arr[i];
}
meanValue = size > 0 ? sum / size : 0;
printf("\nmean: %.3lf", meanValue);
}
The size is the value of k after the input loop is done, so you call it:
mean(num1, k);
Your function needs to pieces of information:
the pointer to the data array;
the size of the array (number of elements).
However, the way you are computing the mean is subjected to bad numeric conditioning (floating point overflow). Here I suggest using the Incremental Averaging instead. Please consider this code:
double mean(double *arr, int num)
{
double res = arr[0];
for (int i = 1; i < num; ++i)
res += (arr[i] - res) / (i+1.0);
return res;
}
Note that I'm assuming you are using a C99 compliant compiler for the integer declaration inside the for loop.

How to code the summation of a function in C?

EDIT: I've added the main, factorial, and trapGamma function to give the full picture but I am specifically talking about the for loop for iSum in the I function.
Basically I've run out of ideas and exhausted everywhere I know of to find an answer to this. I need to code a program that will compute a complex function which represents an M/M/1 queue.
The function includes sub functions such as calculating the integral of a gamma function and computing factorials. I've written all the code for the computations but my sum is giving me huge numbers when I would expect nothing higher than about .35
#include <math.h>
#include <stdio.h>
double I(int k, double t);
double trapGamma(double z);
unsigned long long int factorial(unsigned int n);
int main()
{
int k;
int i = 0;
double dt = 0.1;
printf("Ikx = [ \n");
for (t = 14.0 ; t <= 15.0; t += dt)
{
printf("%f " , t);
for (k = 1 ; k <= 10 ; k++)
{
I(k, t);
printf("%f " , I(k, t));
}
printf("\n");
}
printf(" ];\n");
return (0);
}
double I(int k, double t)
{
unsigned long long int x;
unsigned int n = 20;
double numerator, y, pow1, c;
double iSum;
double Ix;
int i = 0;
iSum = 0.0;
Ix = 0.0;
a = .25 * pow(t , 2);
b = pow(a, i);
x = factorial(n);
y = trapGamma(k + i + 1);
iSum = (b / (x * y));
//This is the sum loop that I'm having trouble with, I've broke the iSum equation down for my own readability while coding right above this comment
for (i = 0; i <= 100 ; i++)
{
iSum += i;
}
Ix = (pow((.5 * t), k) ) * iSum;
return Ix;
}
/*
I've checked both the factorial and trapGamma functions and they are giving me the expected results.
*/
unsigned long long int factorial(unsigned int n)
{
if(n <= 1)
return 1;
else
return (n * factorial(n - 1));
}
double trapGamma (double z)
{
int i , N = 100;
double gamma;
double a = 0.0;
double b = 15.0;
double x1, x2, y1, y2;
double areai;
double w = (b - a) / N;
gamma = 0.0;
for (i = 1; i < N; i++)
{
x1 = a + ((i - 1) * w); //the left bound point
x2 = a + (i*w); //the right bound point
y1 = pow(x1,z - 1)*exp(-x1); //the height of our left bound
y2 = pow(x2, z - 1)*exp(-x2); //the height of our right bound
areai = ((y1 + y2) / 2.0) * (x2 - x1);
gamma += areai;
}
return gamma;
}
This is building upon another project where I used a bessel function to create the M/M/1 queue over a 60 second span so I can see what this one is supposed to be. I've checked both my trapGamma and factorial functions results on there own and they are both working as expected.
How are summations supposed to be coded?
If the intent of the posted code is to calculate the modified Bessel function I, there are some pitfalls and useful semplifications to be aware of. Given
Trying to calculate the factorial, the value of the Gamma function, their product and the powers separately for each term of the sum leads to integer overflow sooner than later.
It's better to update the value of each addend of the sum instead.
Also, given that k is a whole, we have Γ(n) = (n - 1)!
The addends are increasingly smaller and, after some iterations, too small to be added to the sum, given the limited precision of type double.
// Evaluates x^k / k! trying not to overflow
double power_over_factorial(double x, int k)
{
double result = 1.0;
for ( int i = 1; i <= k; ++i )
{
result *= x / i;
}
return result;
}
#define MAX_ITERS 20
double modified_Bessel_I(int k, double x)
{
x /= 2;
const double xx = x * x;
double partial = power_over_factorial(x, k);
double old_sum, sum = partial;
int m = 1;
do
{
old_sum = sum;
partial *= xx / ((m + k) * m);
sum += partial;
}
while ( old_sum != sum && ++m < MAX_ITERS );
return sum;
}
Testable here.

Using functions to solve other functions (sinx, cosx, exp) in C

my professor gave me a confusing problem and I'm completely lost on what to do. Basically he wants me to solve cos(x) and exp(x) (he gave an example for sinx) without using the built in math.h functions. Not only that, but he wants me to use both the fact() and power() functions to solve it. I could most likely solve it through straight math but I'm a bit lost on using the functions. I understand the general concept but I suck at math (especially trig) and I'm not exactly sure what they functions are doing arithmetically. Any helps or points to the right direction will be greatly appreciated.
#include <stdio.h>
#include <math.h>
int main()
{
char more;
double x, mySin(), myCos(), myExp();
printf("\n\n\t\tInput X: ");
scanf("%lf", &x);
do {
printf("\n\n\t\t\tLibraryResult MyResult");
printf("\n\n\tsin< %5.2f> %7.5f %7.5f", x, sin(x), mySin(x));
printf("\n\n\tcos< %5.2f> %f %f", x, cos(x), myCos(x));
printf("\n\n\texp< %5.2f> %f %f", x, exp(x), myExp(x));
printf("\n\n\t\tDo More (Y/N)? ");
scanf("%s",&more);
}
while (more == 'y'||more == 'Y');
}
double power(double x, int n)
{
int i = 0;
double prod = 1.;
for ( ; i++ < n; )
prod = prod * x;
return prod;
}
double fact (int n)
{
int i;
double prod = 1.;
for (i = 1; i <= n; i++)
prod = prod * i;
return prod;
}
double mySin(double x)
{
int i, sign;
double sum = 0;
for (i = 0, sign = 1; i < 21; i++, sign = -sign)
sum = sum + sign * power(x, 2 * i + 1)/ fact(2 * i + 1);
return sum;
}
double myCos(double x)
{
}
double myExp(double x)
{
}

Complex Data Type in C Producing Trouble in Algorithm

I'm trying to perform a calculation which involves the following C-function:
long double complex* tridiag_thomas(long double complex *a, long double complex *b, long double complex *c, long double complex *f, int N) {
long double complex *v; v = (long double complex *)malloc(sizeof(long double complex) * N);
long double complex *y; y = (long double complex *)malloc(sizeof(long double complex) * N);
long double complex w;
int k;
for (k = 0; k < N; k++) {
y[k] = 0;
v[k] = 0;
}
w = a[0];
y[0] = f[0] / w;
for (k = 1; k < N; k++) {
v[k - 1] = c[k - 1] / w;
w = a[k] - b[k] * v[k - 1];
y[k] = (f[k] - b[k] * y[k - 1]) / w;
}
for (k = N - 2; k >= 0; k--) {
y[k] = y[k] - v[k] * y[k + 1];
}
return y;
}
I pass a matrix through this function (f), find y, modify f with y, and pass the new f through the function again. I do this on the order of 1000 times. When working with real values (and making the necessary change of long double complex -> long double), this function works as expected. When using it in the above form with complex arguments, however, the result diverges to infinity very quickly.
Can anybody enlighten me as to why that might be? I'm not new to programming, but I am new to C.
I do see a problem where it is leaking 'v'. This makes me suspect that you are not following the c style assignment at the upper level. We don't have the upper level code.
When is y freed? Does the assignment loop through all the values or are you doing a c++ style assignment? Remember that allocation, assignment, and deallocation do not come for free in c, except for the types built in to the compiler.

Hopalong fractals, checking c synatx

I have written following code in order to produce simple list of double pairs to import in plot program.
#include <stdio.h>
#include <math.h>
int main(void)
{
int i;
double x=2,y=3;
for(i = 0; i < 1000; i++){
x = y- x/fabs(x)*sqrt(fabs(x+0.7));
y = 0.3-x;
printf("%5.4f , %5.4f\n" ,x,y);
}
return 0;
}
I don't get what I expect from this functions. Instead of hopalong fractal I get linear progression graph. Is this only syntax error?
When you assign y, you use the new value of x, which has just been updated. The calculation requires the x value from the last step. Make a copy and use that:
int main(void)
{
double x = 2;
double y = 3;
int i;
for(i = 0; i < 1000; i++) {
double xx = x;
x = y - x/fabs(x)*sqrt(fabs(x + 0.7));
y = 0.3 - xx;
printf("%5.4f , %5.4f\n" ,x,y);
}
return 0;
}

Resources