I'm attempting to print the height y as a function of time t.
EDIT: Alright I got the code to work now, thanks to all of you! I appreciate your help!
#include <stdio.h>
int main() {
double t, g = -9.8, v = 20;
double y;
for(t = 0; t < 4.079; t = t + .02){
y = (( v * t) + ( .5 * g * t * t ));
printf("value of y: %f\n", y);
}
return 0;
}
On this line:
printf("value of y: %d\n", y);
%d is for printing integers (int).
You are trying to print a double.
Use %f to print a double.
You will have to re-calculate the value of y every time in your loop:
for(t = 0; t < 4.079; t = t + .02) {
y = ((v * t) + (.5 * g * ( t * t));
printf("value of y: %d\n", y);
}
pow becomes a reserved word/syntax once you use math.h and compile with the -lm flag linking that math library. pow is then a function from math.h so you cannot use pow as a variable where you do double pow(double t, double s);
It is best, if not just for human readability, to simply declare all your variables first. Then at most, when declaring them, assign them a value like you do for g and v.
Consider this modification to your code:
# include <stdio.h>
# include <math.h>
int main ( void )
{
const double gravity = -9.8; /* don't be afraid to use full words */
double v = 20;
double t, s;
double p; /* changed from pow */
double y;
p = pow( t, s ); /* this is t^s consider using a better variable name than the letter p */
/* for equations like this `y=` below, */
/* putting the textbook definition of it just prior and */
/* and explaining what you are trying to do will help immensely */
/* later on when your program gives the wrong answer and you */
/* are scratching your head trying to figure out why */
/* and especially if it is someone else */
y = (v * t) + (0.5 * gravity * pow(t, 2.0) );
for ( t = 0; t < 4.079; t = t + .02)
{
printf("value of whatever: %lf\n", whatever ); /* original code had %d here, must use %lf because your variables are type double */
}
return 0;
}
Related
guys. I'm a beginner and have to create a function that returns a line of output type Line from inputs y intercept and slope, and create another function that prints it. When I run the functions, it mostly prints right, but x prints as 0.00. I need it to print as an x variable because I will later be making a function that finds the intercept of two lines.
Here's the create function:
Line createLine (double m, double b) {
Line y;
double x;
y.m = m;
y.b = b;
//y = y.m * x + y.b; get an error saying the types dont match so I stopped using this
return y;
The print function:
void displayLine (Line a){
double x;
printf("y = %lf * %lf + %lf\n", a.m, x, a.b);
And the struct:
typedef struct line_struct{
double m;
double b;
} Line;
I also have a point struct if it matters.
You're assuming the variable x will get printed as the output, but the way you've desired won't work. The x is an identifier name and hence, it can't be used to print its name itself.
Thus, you don't need to use any other stuff here at all. Just simply print x in the printf() statement and you're done.
Also, note that, as per of your requirement, we've used int datatype here rather than using double, the double is only required when you need to show a very large floating point value which can't be held by the float itself.
You may try this way to achieve:
#include <stdio.h>
struct line_struct {
int m;
int b;
} Line;
Line createLine(int m, int b) {
Line y;
y.m = m;
y.b = b;
return y; // returning the initialized struct to the function correctly
}
void displayLine (Line a){
printf("y = %dx + %d\n", a.m, a.b); // displaying a simple 'x'
}
int main(void) {
Line l;
l.b = 3;
l.m = 4;
displayLine(l);
return 0;
}
This will give you the desired output:
y = 4x + 3
If all you want is to print the line y = 4x + 3, you don't need a variable called x at all. This will suffice:
printf("y = %lf x + %lf\n", a.m, a.b);
I think the error is in the createLine function.
I hope it works this way.
Line createLine (double m, double b) {
Line y;
double x;
y.m = m*x;
y.b = b;
return y;
}
i wrote a program who can read the Original YUV-file and add Gaussian noise with mean 0 to the Modified one.
the problem is that i don't know how to implement the Polar function on the main function, when i tried its always generate errors.
anyone have any ideas to solve my problem.
thanks
void polar(double *x1, double *x2)
{
double u, v, q, p;
do {
u = 2.0 * random() - 1;
v = 2.0 * random() - 1;
q = u * u + v * v;
} while (q >= 1.0 || q == 0.0);
p = sqrt(-2 * log(q) / q);
*x1 = u * p;
*x2 = v * p;
}
int main(void)
{
FILE *fp1, *fp2;
int a;
double a1,a2;
fp1= fopen("FOOTBALL_352x288_30_orig_01.yuv","rb");
fp2= fopen("FOOTBALL_352x288_30_orig_02.yuv","wb");
int tab[10]="";
while(!feof(fp1))
{
fread(tab,sizeof(int),1,fp1);
fwrite(tab,sizeof(int),1,fp2);
}
fclose(fp1);
fclose(fp2);
return 0;
}
The polar function expects the address of two doubles as inputs. If you declared a1 and a2 to be passed into polar, you can call polar(&a1, &a2). The polar function will have set the a1 and a2 by the time it returns. To check this, try printing these variables before and after your call to the polar function.
I am trying to use a function that will calculate values for h and then input these values of h into an equation that will calculate n. This is what my code currently looks like...
int findN(double xI, double xF) {
double h = 0.1;
int n;
do {
printf_s("%8.5f \n", h);
n = ((xF - xI) / h);
h = h / 10;
printf_s("%6d \n", n);
} while (h >= 0.00001);
return n;
}
I know that this function will only return n currently, but as i am new to this i am unsure as to how to also return all the values of h as well as all the values of n... If someone could assist me and show me how to return all the values for n & h, it would be much appreciated.
Thanks.
Typical approach to return multpile values is using arrays and pass its pointer to function:
int f(double *h) {
h[0] = 1.1;
h[1] = 2.2;
}
int main()
{
// create pointer
double *h;
// initialize it with memory block
h = malloc(2*sizeof(double));
// call the function
f(h);
// show output
printf_s("%8.5f \n", h[0]);
printf_s("%8.5f \n", h[1]);
// release memory block
free(h);
return 0;
}
Also same array may be created without memory allocation. It is more simple but arrays exists only until execution is not leave away from function scope where it declared.
int main()
{
// create array
double h[2];
// call the function
f(h);
// show output
printf_s("%8.5f \n", h[0]);
printf_s("%8.5f \n", h[1]);
return 0;
}
And if you can know count of element only during function call you can allocate array in function and return array by pointer and release array at caller.
double* f() {
// create pointer
double *h;
// some size calculations
int size = 1+1;
// initialize it with memory block
h = malloc(size*sizeof(double));
// fill the array
h[0] = 1.1;
h[1] = 2.2;
// return array by pointer
return h;
}
int main()
{
// create pointer
double *h;
// call the function
h = f();
// show output
printf_s("%8.5f \n", h[0]);
printf_s("%8.5f \n", h[1]);
// release memory block
free(h);
return 0;
}
There are many ways to solve this. Another is to return a struct.
Below, findN() returns one object. It just happens that the object contains two members. This approach is suitable when with small objects. With large objects,other approaches should be considered.
typedef struct {
int n;
double h;
} nh;
nh findN(double xI, double xF) {
nh retval;
retval.h = 0.1;
do {
printf_s("%8.5f\n", retval.h);
retval.n = ((xF - xI) / retval.h);
retval.h = retval.h / 10;
printf_s("%6d\n", retval.n);
} while (retval.h >= 0.00001);
return retval;
}
// usage exanple
nh y;
y = findN(1.23, 4.56);
printf_s("h:%8.5f, n:%6d\n", y.h, y.n);
Read into pointers if you want to learn more. But essentially by sending h as a pointer it will return it's value to main.
#include <stdio.h>
int findN(double xI, double xF, double h[]) {
int i = 0;
int n;
h[i] = 0.1;
do {
i++;
printf_s("%8.5f \n", *h);
n = ((xF - xI) / (*h));
h[i] = h[i-1] / 10;
printf_s("%6d \n", n);
} while (h[i] >= 0.00001);
return n;
}
int main()
{
double h[100];
double xI = 1.0, xF = 1.0;
int n;
n = findN(xI, xF, h);
return 0;
}
Read pointers,you will be able to return as many values you want to return,when calling function through main add &h in actual parameters,it means findN(xI,xF,&h) and in declaring the function findN add double *h in formal parameters,that is int findN(double xI,double xF,double *h)...."meaning of * is -value at address of....meaning of & is address of.This will make changes in h globally in this program as the vale is changing in its address.You can return even more values like this using more variables.This is called returning values indirectly.Vote for my answer if its applicable.
The simplest way to handle this is change the function to accept pointers to variables that will accept the values of n and h. Then the function will dereference those pointers to update the relevant variables in the calling function.
void findN(double xI, double xF, int *ret_n, double *ret_h)
{
...
*ret_n = n;
*ret_h = h;
}
Then you can call your function like this:
int n;
double h;
findN(1.2, 3.4, &n, &h);
This method is fine for a relatively small number of parameters. If the number of parameters gets to be too large, you can instead create a struct containing all of the values to be returned either pass in the address of the struct or just return the struct outright.
I'm new to C, and quite unfamiliar with writing any program larger than a few lines.
I'm trying to write a model for an object in freefall acted upon by gravity and drag. It uses Eulers method to solve two first order differential equations, one for position and one for velocity.
So we have: F = m dv/dt = -mg - k|v|v and dy/dt = v
These are solved by: Vn+1 = Vn - (delta t*(g+(k/m)|Vn|Vn)) and Yn+1 = Yn + (delta t * Vn)
(In this Vn+1 is the n+1th term etc.)
In my program i've tried to have two functions, for position and velocity, which work by passing pointers with Y and V values between them and the main function, and it should then loop until Y=0 and print off the values at each step.
When I run it it comes up with something like this: http://imgur.com/DNHIhHI
Could anyone tell me either what is wrong with this, or if I need to use a different approach completely?
Many Thanks, Code below
#include <stdio.h>
void Velocity(double *ptr, double m, double k, double t);
void Position(double *pst, double *ptr, double t );
int main()
{
double k = 18833.5608;
double t = 0;
double m;
double speed = 0;
double *ptr = &speed;
double y = 1000;
double *pst = &y;
printf("Enter mass of object: \n");
scanf("%f" , &m);
do
{
Velocity( ptr, m, k, t );
printf("Velocity at time %f is: %f\n" , t, speed);
Position( pst, ptr, t);
printf("Position at time %f is: %f\n" , t , y);
t++;
}
while((y>0));
return 0;
}
void Velocity(double *velo, double m, double k, double t)
{
double g = 9.80665;
*velo = *velo - (t*(g+((k/m)*fabs(*velo)**(velo))));
}
void Position(double *Y , double *velo, double t )
{
*Y = *Y+(t*(*velo));
}
When writing programs that do calculations -- in any language, not just C -- try to make the code that does the computation take arguments and return results but not mutate variables. That is, do not write:
void do_calculation( double * result, double x, double y)
{
*result = x + y;
}
...
double r;
do_calculation(&r, 123, 456);
instead write
double do_calculation(double x, double y)
{
return x + y;
}
...
double r = do_calculation(123, 456);
Make sense?
If you want to modify an existing value, again, don't pass it in as a variable to be mutated. Instead of
void do_calculation(double * accumulator, double x, double y)
{
*accumulator = *accumulator + x + y;
}
...
double r = 10;
do_calculation(&r, 123, 456);
instead say
double do_calculation(double original, double x, double y)
{
return original + x + y;
}
...
double r = 10;
r = do_calculation(r, 123, 456);
Now, once you've got your program architected more sensibly, you need to learn how to debug small programs. Some good advice on that subject can be found here:
http://ericlippert.com/2014/03/05/how-to-debug-small-programs/
A misconcept. I believe you're trying to solve the equations by using small increments of time. Nothing wrong with that, just make the time increment as small as possible, and correct the formulas:
#include <stdio.h>
#include <math.h>
void Velocity(double *velocity, double m, double k, double t)
{
double g = 9.80665;
double velo = *(velocity);
velo = velo - (t*(g+((k/m)*abs(velo)*(velo))));
*(velocity)=velo;
}
void Position(double *position , double *velocity, double t )
{
double Y = *(position);
double velo = *(velocity);
Y = Y+(t*(velo));
*(position)=Y;
}
int main()
{
double k = 18833.5608;
double t = 0;
double dt = 0.001; //making a small increment of time
double m=100;
double speed = 0;
double y = 1000;
//printf("Enter mass of object: \n");
//scanf("%f" , &m);
do
{
Velocity( &speed, m, k, dt );
printf("Velocity at time %f is: %f\n" , t, speed);
Position( &y, &speed, dt);
printf("Position at time %f is: %f\n" , t , y);
t+=dt; //increment time by delta t
}
while((y>0));
return 0;
}
The code line: gsl_blas_daxpy(-a,&gsl_matrix_column(D, q).vector,y);
cause the error
error C2102: '&' requires l-value
, now the problem is that I have no control of the GSL functions so I don't know how to figure this out (removing the "&" didn't work)
afterwards i get
error C2198: 'gsl_blas_daxpy' : too few arguments for call
I'm using Visual studio 2010.
GSL_EXPORT int gsl_blas_daxpy (double alpha,
const gsl_vector * X,
gsl_vector * Y);
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h>
#define M (10) // Number of columns in dictionary */
#define N ((int)(M/2)) // Number of rows in dictionary */
int K = 0.07*M; //Number of non-zero elements in signal - the sparsity
int P=1; //number of signals
double epsilon = 1.0e-7; // Residual error
int numOfIterations = N; /* Max num of iterations - same as num of elements in signal */
double sign(double x){return (x>=0) - (x<0);} // Sign function
int main(int argc, char** argv)
{
int n, m, k, iter, q;
double normi, normf, tmp , norm=sqrt(N), htime;
gsl_matrix *D; // A random dictionary used for encoding the sparse signal NxM
gsl_vector *x; // Sparse info signal (encoder input) MxP
gsl_vector *z; // Evaluated Sparse info signal (decoder output) MxP
gsl_vector *r; // Residual error vector MxP
gsl_vector *y; // Sparse representation of signal (encoder output) NxP
gsl_vector_view v;
clock_t start; //for measuring performance
printf("\nDictionary is:NxM=%dx%d,and the signal sparsity is K=%d", N, M, K);
srand(time(NULL)); //Initialize srand
start =clock(); //Initialize clock
/* Initiallize D as a Bernoulli random dictionary */
D = gsl_matrix_alloc (N, M);
for(m=0; m<M; m++)
{
for(n=0; n<N; n++)
{
tmp=sign(2.0*rand()/(double)RAND_MAX-1.0)/norm;
gsl_matrix_set (D, n, m, tmp); //D[n,m]=tmp
}
}
/* Create a random K-sparse info signal */
x = gsl_vector_alloc(M);
for(k=0; k<K; k++)
{
gsl_vector_set(x, rand()%M, 2.0*rand()/(float)RAND_MAX - 1.0); //put random values at k random positions
}
/* Allocate memory for solution (evaluated signal) */
z = gsl_vector_calloc(M);
/* Allocate memory for residual vector */
r = gsl_vector_calloc(M);
/* Allocate memory for the encoded signal vector (its representation) */
y = gsl_vector_alloc(N);
htime=((double)clock()-start)/CLOCKS_PER_SEC;
printf("\nTime data allocation: %f", htime);
/* Encoding the signal (x to y) */
start = clock();
gsl_blas_dgemv(CblasNoTrans, 1, D, x, 0, y); // y = Dx
htime=((double)clock()-start)/CLOCKS_PER_SEC;
printf("\nTime for encoding: %f", htime);
/* Decoding the signal */
start = clock();
normi = gsl_blas_dnrm2(y); // ||y|| (L2 norm)
epsilon = sqrt(epsilon * normi);
normf = normi;
iter = 0;
/*iterate till the computational error is small enough*/
while(normf > epsilon && iter < numOfIterations)
{
gsl_blas_dgemv(CblasTrans, 1, D, y, 0, r); // r=D'*y
q = gsl_blas_idamax(r); //index of max element in residual vector
tmp = gsl_vector_get(r, q); //the max element in r
gsl_vector_set(z, q, gsl_vector_get(z, q)+tmp); // z[q]=z[q]+ tmp
v=gsl_matrix_column(D, q); // choose the dictrionary's atom (coloum) with the index of largest element in r
gsl_blas_daxpy(-tmp,&v.vector,y); // y = y-tmp*v
normf = gsl_blas_dnrm2(y); // ||y|| (L2 norm)
iter++;
}
htime = ((double)clock()-start)/CLOCKS_PER_SEC;
printf("\nTime for decoding: %f", htime);
tmp = 100.0*(normf*normf)/(normi*normi); // the error at end of algorithm
printf("\nComputation residual error: %f",tmp);
/* Check the solution (evaluated signal) against the original signal */
printf("\nSolution (first column),Reference (second column):");
getchar(); // wait for pressing a key
for(m=0; m<M; m++)
{
printf("\n%.3f\t%.3f", gsl_vector_get(x, m),gsl_vector_get(z, m));
}
normi = gsl_blas_dnrm2(x);
gsl_blas_daxpy(-1.0, x, z); // z = z-x
normf = gsl_blas_dnrm2(z); // ||z|| (L2 norm)
tmp = 100.0*(normf*normf)/(normi*normi); //final error
printf("\nSolution residual error: %f\n",tmp);
/* Memory clean up and shutdown*/
gsl_vector_free(y); gsl_vector_free(r);
gsl_vector_free(z); gsl_vector_free(x);
gsl_matrix_free(D);
getchar();
return EXIT_SUCCESS;
}
gsl_matrix_column(D, q).vector is an R-value. You can't take its address. You need an L-value, so assign it to a named variable first, then pass the address of that variable to the function.
If you make a more permanent home for the return value of gsl_matrix_column, (this particular) problem will go away.
Here is some simplified code that illustrates how one might capture a return value in an addressable slot:
struct _foo {
int i;
};
struct _foo bar () {
struct _foo result = { 5 };
return result;
}
/* won't compile; 'lvalue required as unary & operand */
void qux () {
int *j = &bar().i;
}
/* compiles OK */
void qal () {
struct _foo result = bar();
int* j = &result.i;
}
gsl_vector_view c=gsl_matrix_column(D, q);
gsl_blas_daxpy(-a,&c.vector,y);
I think, introducing a temporal variable led you pass a pointer to it to the function.
EDIT: Well, trying to understand the problem, I wanted to know what the function expect:
int gsl_blas_daxpy (double alpha, const gsl_vector * x, gsl_vector * y)
and
gsl_vector_view gsl_matrix_column (gsl_matrix * m, size_t j)
witj some explanation:
A vector view can be passed to any subroutine which takes a vector
argument just as a directly allocated vector would be, using
&view.vector.
and an example:
for (j = 0; j < 10; j++)
{
gsl_vector_view column = gsl_matrix_column (m, j);
double d;
d = gsl_blas_dnrm2 (&column.vector);
printf ("matrix column %d, norm = %g\n", j, d);
}
Now we have another problem:
Here another answer:
Are you aware that int K= 0.7 is K=0 ??
#define M (10) // Number of columns in dictionary */
int K = 0.07*M; //Number of non-zero elements in signal - the sparsity
alloc do not initialice the vector x. x will contain garbage values, not 0. Did you meant x = gsl_vector_calloc(M); with c? It will set x to 0.
/* Create a random K-sparse info signal */
x = gsl_vector_alloc(M);
for(k=0; k<K; k++) // K=0, for get skiped and x not modified.
{
gsl_vector_set(x, rand()%M, 2.0*rand()/(float)RAND_MAX - 1.0); //put random values at k random positions
}
(And here you will have at most K random values, but possible lest)