I want to collect polar coordinate values by converting them to Cartesian values in C.
But I'm getting wrong values at 12°:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <complex.h>
int main()
{
int desire=1;
int wind[desire];
for (int i = 0; i < desire; i++)
{
printf("\nEnter degree of wind:");
scanf("%d",&wind[i]);
}
double complex sum=0;
for (int i = 0; i < desire; i++)
{
sum=cos(wind[i])+ sin(wind[i]) * I;
}
double convert(double radian);
printf("\n %.2f %.2fi",creal(sum),cimag(sum));
double r =hypot(creal(sum),cimag(sum));
double angle= convert(atanf(creal(sum)/cimag(sum))) ;
printf("\n %.2f %.2f",r,angle);
return 0;
}
returning completely wrong sine(imaginary value)
0.84 -0.54i
1.00 -57.55
It should print0.97 +0.20i not 0.84 -0.54i.
What is wrong?
The convert function:
#include <math.h>
#include "convert.h"
double convert(double radian)
{
return(radian * (180/M_PI));
}
Per 7.12.4.6 The sin functions (bolding mine):
The sin functions compute the sine of x (measured in radians).
cos() is similar.
You're entering 12 radians.
Related
When trying to plot the solution of the heat PDE I've found some troubles. The solution that I've found is:
Here is the code:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#define N 10000
double f(double x);
double X[N];
double Y[N];
int main(){
int i;
double b=43351/94400;
double dx=0.0001;
X[0]=0;
Y[0]=b;
for (i=1; i<N; i++){
X[i]=X[i-1]+dx;
Y[i]=f(X[i]);
}
FILE* output;
output = fopen("dades.txt", "w");
fprintf(output, "x Posició Temperatura\n");
for (i = 0; i < N; i++){
fprintf(output, "%lf %lf %lf\n", i*dx, X[i], Y[i]);
}
fclose(output);
return 0;
}
double f(double x){
int n;
double b=43351/94400;
for (n=1; n<N; n+=2){
double pi=3.14159265358979323846;
double t0=0.025;
double result=b;
result+=2*(1-pow((-1),n))/(pi*n)*(1-exp(-pow(n,2)*pow(pi,2)*pow(t0,2)))/(pow(n,2)*pow(pi,2))*sin(n*pi*x);
}
return result;
}
What I'm trying to do is to declare a function that calculates the infinite sum for n odd, and then looping it for every x between 0 and 1. The problem is that I don't know how to declare "result" in order to be the sum of all the terms, because if I declare it outside the for loop it doesn't satisfy the boundary conditions.
(Note that I fixed t=0.025).
According to the equation, you can implement f as:
#define M_PI 3.14159265358979323846;
double f(double x)
{
int n;
double result=43351.0/94400.0;
double t0=0.025;
for (n=1; n<N; n+=2){
result+=2*(1-pow((-1),n))/(M_PI*n)*(1-exp(-pow(n,2)*pow(M_PI,2)*pow(t0,2)))/(pow(n,2)*pow(M_PI,2))*sin(n*M_PI*x);
}
return result;
}
Since you are using double, so you have to explicitly add a .0 otherwise it may be considered as integer.
The declarations of variable are moved outside the loop in order both to clarify the code and ensure the variable result gets update instead of being overwritten.
EDIT:
You could improve the function f to take the value of t as an input. This also aligns with the equation provided. It would then implements this way:
double f(double x, double t)
{
int n;
double result=43351.0/94400.0;
for (n=1; n<N; n+=2){
result+=2*(1-pow((-1),n))/(M_PI*n)*(1-exp(-pow(n,2)*pow(M_PI,2)*pow(t,2)))/(pow(n,2)*pow(M_PI,2))*sin(n*M_PI*x);
}
return result;
}
EDIT:
The implementation of the math of the equation could be further simplified:
a^2 b^2 is same as (ab)^2.
(-1)^n with n odd is always -1.
2*(1-pow((-1),n)) is a replacement for 4.
Plus, from a performance perspective you can avoid recalculation of repeated terms by putting them in a variable and the use it as you need (for instance the n^2 pi^2).
this is the following code:
#include <stdio.h>
#include <math.h> //to use 'sin()' function
int main() {
double i = 0;
//printing the values of sine table
printf("SINE TABLE :\n\n");
while (i <= 90) {
printf("sin(%.0lf)=%lf\n", i, sin(i * 3.1415 / 180.0));
i += 15;
}
double angle_degree = 90;
//printing the values of cosine table
printf("COSINE TABLE :\n\n");
while (angle_degree >= 0) {
printf("cos(%.0lf)=%lf\n", angle_degree, cos(angle_degree * 3.1415 / 180.0));
i -= 15;
}
return 0;
}
I am getting the correct value for some code i.e It printing the sine table correctly.
SINE TABLE :
sin(0)=0.000000
sin(15)=0.258819
sin(30)=0.500000
sin(45)=0.707107
sin(60)=0.866025
sin(75)=0.965926
sin(90)=1.000000
but for cosine table the loop getting the value of cos(90)=0.0000
can you please tell me what is wrong in my program , it will help me to print the correct cosine table....?
Your program runs an infinite loop because you decrement i instead of angle_degree.
Also note that your approximation of π is inaccurate. You should use the constant M_PI defined on POSIX systems or a more precise approximation.
Here is a modified version:
#include <math.h>
#include <stdio.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846264338327950288
#endif
int main() {
double i = 0;
//printing the values of sine table
printf("SINE TABLE:\n\n");
while (i <= 90) {
printf("sin(%.0f)=%f\n", i, sin(i * M_PI / 180.0));
i += 15;
}
double angle_degree = 90;
//printing the values of cosine table
printf("COSINE TABLE:\n\n");
while (angle_degree >= 0) {
printf("cos(%.0f)=%f\n", angle_degree, cos(angle_degree * M_PI / 180.0));
angle_degree -= 15;
}
return 0;
}
Because you are using angle_degree not i.
You can also use for loop to iterate this, you'll less likely to do this kind of mistake.
#include <stdio.h>
#include <math.h>
int main()
{
for(double i=0;i<=90;i+=15){
printf("sin(%.0lf)=%lf\n", i, sin(i * M_PI / 180.0));
}
for(double j=90;j>=0;j-=15){
printf("cos(%.0lf)=%lf\n", j, cos(j * M_PI / 180.0));
}
return 0;
}
You can also use M_PI which is more accurate than 3.1415. Because when you calculate cos(90°) using 3.1415, you will get 0.000046
cos(90*M_PI/180)=0;
cos(90*3.1415/180)=0.000046
You can look base on this answer https://stackoverflow.com/a/9912169/5215171
I have a project going in two files, but I cannot get the main program to print out the average variable, I just get 0.0 no matter what I change. It also does not print out a whole other function Any Tips?
Main File:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
float average(void);
float std_dev(float);
float output(float);
float array[10] = {4.8, 12.98, 82.1, 5.98, 19.75, 24.9, 75.7, 3.45, 10.0, 28.11};
extern float avg;
int main()
{
float s = 0.0;
printf("The average value of the array is %.2f \n", avg);
s = std_dev(avg);
printf("The standard deviation of the array is %.2f \n", s);
return 0;
}
static void output(float var)
{
printf("The value of the variable is %.2f \n", var);
}
Second File:
#include <math.h>
extern float array[];
float avg = 26.78;
static float average()
{
int n;
float sum = 0.0, mean=0.0;
for(n=0; n<10; n++)
sum = sum + array[n];
mean= sum/10;
output(mean);
return mean;
}
float std_dev()
{
int n;
float cumm_diff = 0.0;
for(n=0; n<10; n++)
cumm_diff += (avg -array[n]) * (avg -array[n]);
return sqrt(cumm_diff/10);
}
the following proposed code:
cleanly compiles
performs the desired functionality
demonstrates how to execute functions in external files
properly prototypes the functions
removes extraneous code
properly formats the code for ease of readability and understanding
eliminates the 'magic' numbers
lets the compiler determine how many items are in the array
uses float literals rather than double literals
documented why each of the system header files is included
used meaningful parameter and variable names
derived the value of count at compile time
cast the int count parameter, when needed, to a float
and now the proposed code:
header file: main.h
#ifndef MAIN_H
#define MAIN_H
void output(float var);
extern float avg;
#endif // MAIN_H
header file: util.h
#ifndef UTIL_H
#define UTIL_H
float calc_std_dev( float *, int );
void calc_mean( float *, int );
#endif // UTIL_H
main.c file
#include <stdio.h> // printf()
#include "main.h"
#include "util.h"
float array[] =
{
4.8f, 12.98f, 82.1f, 5.98f, 19.75f,
24.9f, 75.7f, 3.45f, 10.0f, 28.11f
};
int main( void )
{
printf("The average value of the array is %.2f \n", avg);
float s = calc_std_dev( array, sizeof(array)/sizeof(float) );
printf("The standard deviation of the array is %.2f \n", s);
calc_mean( array, sizeof(array)/sizeof(float) );
return 0;
}
void output(float var)
{
printf("The mean value of the array is: %.2f \n", var);
}
util.c file
#include <math.h> //sqrtf()
#include "main.h"
#include "util.h"
float avg = 26.78f;
void calc_mean( float array[], int count )
{
int n;
float sum = 0.0f;
float mean = 0.0f;
for(n=0; n<count; n++)
sum = sum + array[n];
mean= sum/ (float)count;
output(mean);
}
float calc_std_dev( float array[], int count )
{
int n;
float cumm_diff = 0.0f;
for(n=0; n<count; n++)
cumm_diff += (avg -array[n]) * (avg -array[n]);
return sqrtf(cumm_diff / (float)count);
}
You never call your function average(), which is why the average is not computed, but the initialized value avg = 26.78 (not 0 - you probably changed that at some point) is printed and used by std_dev().
I have a problem with entering a function (in C), it will give a segmentation fault when I try to enter calc_uq() from the function dynamical_matrix(). When I try to compile it, it will still print check5, but it will give a segmentation fault before printing checkA.
This problem only occurs to me with I choose a large amount of timesteps (steps=100000), for steps=75000 it still works.
Below is part of my code, the main function, the dynamical_matrix() function and the calc_uq() function.
I hope someone can help me with this problem.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <stdbool.h>
#include <complex.h>
#define MAX 1000 //max aantal deeltjes
#define NDIM 3
#define npart 108
#define steps 100000
#define kint 1
//d is distance squared
int s=20000; //calculations start at time = s.
double pi=3.14159265359;
double radius=0.5;
double r2[npart][NDIM];
double r[steps][npart][NDIM], R[steps][npart][NDIM], RC[steps][npart][NDIM]; //r is with periodic boundary, R without, RC = R-CoM
double CoM[steps][NDIM];
double box;
double mean[npart][NDIM];
double complex uq[steps][NDIM];
double complex Dq[3][3];
double ui[steps][npart][NDIM];
double sqrtN,beta=1;
double k[3];
main()
{
int i,p,t=0;
readparts();
init_random_seed();
sqrtN=sqrt(npart);
k[0]=1*(2*pi/box)*(kint);
k[1]=0*(2*pi/box)*(kint);
k[2]=0*(2*pi/box)*(kint);
for(i=0;i<npart;i++)
{
r[t][i][0]=r2[i][0];
r[t][i][1]=r2[i][1];
r[t][i][2]=r2[i][2];
}
t++;
writedata();
for(p=1;p<steps*100;p++)
{
random_particle_displacement();
if(p%100==0)
{
for(i=0;i<npart;i++)
{
r[t][i][0]=r2[i][0];
r[t][i][1]=r2[i][1];
r[t][i][2]=r2[i][2];
}
if((t+1)%1000==0){printf("t=%d\n",(t+1));}
t++;
}
if(p%1000==0){writedata();}
}
printf("check1\n");
dynamical_matrix();
print_Dq();
print_R72();
print_uq();
}
calc_uq()
{
printf("checkA\n");
double complex arg[npart];
double complex sum[steps][NDIM];
int i,t;
printf("check6\n");
for(i=0;i<npart;i++)
{
arg[i]=I * ( k[0]*mean[i][0] + k[1]*mean[i][1] + k[2]*mean[i][2] );
printf("arg[%d]=%fI\tmean[%d][0]=%f\tmean[%d][1]=%f\tmean[%d][2]=%f\n",i,cimag(arg[i]),i,mean[i][0],i,mean[i][1],i,mean[i][2]);
}
printf("check7\n");
for(t=0;t<steps;t++)
{
sum[t][0]=0;
sum[t][1]=0;
sum[t][2]=0;
for(i=0;i<npart;i++) //calculate the Fourier sum.
{
ui[t][i][0]=RC[t][i][0]-mean[i][0]; //calculate the displacement from its mean position
ui[t][i][1]=RC[t][i][1]-mean[i][1];
ui[t][i][2]=RC[t][i][2]-mean[i][2];
sum[t][0]+=cexp(arg[i])*ui[t][i][0];
sum[t][1]+=cexp(arg[i])*ui[t][i][1];
sum[t][2]+=cexp(arg[i])*ui[t][i][2];
}
uq[t][0] = sum[t][0]/sqrtN; //uq at timestep t
uq[t][1] = sum[t][1]/sqrtN;
uq[t][2] = sum[t][2]/sqrtN;
}
printf("check8\n");
}
dynamical_matrix()
{
printf("check2\n");
double complex uquq[steps][NDIM];
double complex uquqmean[3][3];
printf("check3\n");
int i,j,t;
calc_R();
calc_CoM();
calc_RC();
printf("check4\n");
for(i=0;i<npart;i++)
{
calc_mean_pos(i);
}
printf("check5\n");
calc_uq();
//calculate <uq*.uq>
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
uquqmean[i][j]=calc_uquqmean(i,j);
Dq[i][j]=1/(beta*uquqmean[i][j]);
}
}
I am using the trapezium rule to calculate the integral of a function between 0 and infinity. I can calculate the value of the integral for a given value of N, and now I am trying to loop N from two to a given value but it will not work. It keeps calculating the value of the integral for when N is 2 and repeating instead of the new value of N. The problem is in the for loop in main() I think.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <float.h>
double f(double x) {
double a;
a =1/((1+x)*pow(x,0.5));
return a;}
double tra(double upper, double lower, int N) {
double sum, step, integral,lowest;
step=(upper-lower)/(N-1);
lower=lower+step;
if(lower==0) {
lowest=DBL_EPSILON;}
else {
lowest=lower;}
while(lower<upper) {
sum=sum+f(lower);
lower=lower+step;}
integral=step*(sum+(f(upper)/2)+(f(lowest)/2));
sum=0;
return integral;}
main() {
int N;
double upper=DBL_EPSILON*2, lower=0, total=0;
for(N=2;N<20000;N+=100) { /*Here im trying to loop N so that the integral is calculated for increasing values of N*/
while(upper<FLT_MAX) {
total=total+tra(upper, lower, N);
lower=upper;
upper=upper*2;}
printf("Integral is %.10f\n", total);
}
}
I suggest you move the variable initialisation to within the for loop like this:
int main(void) {
int N;
double upper, lower, total;
for(N=2;N<20000;N+=100) {
upper = DBL_EPSILON*2;
lower = 0;
total = 0;
while(upper<FLT_MAX) {
total=total+tra(upper, lower, N);
lower=upper;
upper=upper*2;
}
printf("Integral is %.10f\n", total);
}
return 0;
}