Normalize a Vector from a struct in C - c

typedef struct
{
float x, y, z;
} VECTOR;
Write a function that takes a pointer to a VECTOR structure and normalizes the x, y, and z components
I realize you can normalize the Vector by getting the length and dividing x, y, and z by the length. but how would I do this with the code presented here.
Here is my attempt at this.
Void Norm(*VECTOR)
{
x = x / *VECTOR.Length;
y = y / *VECTOR.Length;
z = z / *VECTOR.Length;
}

#include <math.h>
typedef struct
{
float x, y, z;
} VECTOR;
void normalize( VECTOR* p )
{
float w = sqrt( p->x * p->x + p->y * p->y + p->z * p->z );
p->x /= w;
p->y /= w;
p->z /= w;
}

Related

Pointers and interchange with C

I have a general idea of how to do this, as you can see by the code I did below. The only problem I am having is finishing the interchange part. Basically, what I am trying to do is move the value of the lowest variable into the 1st variable, the second middle value to the 2nd variable, and the biggest to the 3rd variable.
I know I do this with the interchange and using temp somehow, but how would I complete that, because with three values temp would get overridden somehow. What am I missing? So basically a = 4.0, b = 7.0, c = 1.0, c (1.0) needs to go into a, a (4.0) needs to go into b, and b (7.0) needs to go into c.
Thanks!
#include <stdio.h>
void interchange(double * x, double * y, double * z);
int main(void)
{
double a = 4.0, b = 7.0, c = 1.0;
printf_s("Originally a = %d, b = %d, and c = %d.\n", a, b, c);
interchange(&a, &b, &c);
printf_s("Now, a = %d, b = %d, and c = %d.\n", a, b, c);
return 0;
}
void interchange(double * x, double * y, double * z)
{
double temp;
temp = *z;
*y = *z;
* = temp
// what am I missing here? I cant get my head around this above ^^^
}
Thanks for the guidance!
Something like:
void swap(double* first, double* last){
double temp = *first;
*first = *last;
*last = temp;
}
void interchange(double * x, double * y, double * z){
if(*x > *y) swap(x, y);
if(*y > *z) swap(y, z);
if(*x > *y) swap(x, y);
}
the simplest way is:
if (*x > *y) {
temp = *x; // store value of x
*x = *y; // overwrite x with y
*y = temp; // overwrite y with x (which is in temp)
}
// now we sure that x <= y
if (*y > *z) {
temp = *z;
*z = *y;
*y = temp;
}
// now we sure that x <= z and y <= z, but we don't know x/y relationships
if (*x > *y) {
temp = *x;
*x = *y;
*y = temp;
}
// now x <= y <= z

Error in main subscripted value in C

I'm new to C and I'm trying to calculate the kinetic energy from certain values (px and py) but my routine accuses always as main mistake subscripted value is neither array nor pointer vector nor. Can anyone help me because all I know I've tried.
The error occurs in the kinetic function
thanks
My routine
#include <stdio.h>
#include <stdlib.h>
#ifndef RAN2_H_
#define RAN2_H_
void UniformBox(long, long *, double, double, double *, double *, double *, double *);
void kinetic(long, double, double, double);
#endif /* RAN2_H_ */
#include "ran2.h"
float ran2(long*);
void UniformBox(long n, long *idum, double L, double p0, double *rx, double *ry, double *px, double *py){
long i;
for(i = 0 ; i < n ; i++){
rx[i] = ((double)ran2(idum))*L;
ry[i] = ((double)ran2(idum))*L;
px[i] = ((double)ran2(idum) -.5)*2*p0;
py[i] = ((double)ran2(idum) -.5)*2*p0;
}
return;
}
void kinetic(long n, double x, double y, double kint){
long i;
for(i = 0 ; i < n ; i++){
kint[i] = (x*x)+(y*y);
}
return;
}
void UniformBox(long, long *, double, double, double *, double *, double *, double *);
void kinetic(long n, double x, double y, double kint);
int main(){
long i, n, seed, idum;
double *rx, *ry, *px, *py;
double L, p0, kint;
n = 1000;
L = 2.0;
p0 = 1.22;
seed = 10;
idum = -seed;
FILE *init = fopen("initialPosition.dat", "w");
rx = (double *) malloc((double) n * sizeof(double));
ry = (double *) malloc((double) n * sizeof(double));
px = (double *) malloc((double) n * sizeof(double));
py = (double *) malloc((double) n * sizeof(double));
UniformBox(n, &idum, L, p0, rx, ry, px, py);
kinetic(n, px, py, kint);
for(i = 0 ; i < n ; i++){
printf("%lf\t%lf\t%lf\t%lf\t%lf\n", rx[i], ry[i], px[i], py[i], kint[i]);
fprintf(init,"%lf\t%lf\t%lf\t%lf\n", rx[i], ry[i], px[i], py[i]);
}
fclose(init);
free(rx);
free(ry);
free(px);
free(py);
return 0;
}
I've fixed the compile errors. A few things to note.
I removed multiple incompatible function prototypes.
Aside from kinetic's kint needing to be a pointer, x and y needed to be pointers. Note that this is conjecture on my part, based on the totality of the code. Also note the change inside the loop from x to x[i]. Otherwise, things didn't make sense [to me].
In main, I added a malloc for kint
Anyway, here's the code [please pardon the gratuitous style cleanup]:
#include <stdio.h>
#include <stdlib.h>
#ifndef RAN2_H_
#define RAN2_H_
float ran2(long *);
#endif /* RAN2_H_ */
//#include "ran2.h"
void
UniformBox(long n, long *idum, double L, double p0, double *rx, double *ry,
double *px, double *py)
{
long i;
for (i = 0; i < n; i++) {
rx[i] = ((double) ran2(idum)) * L;
ry[i] = ((double) ran2(idum)) * L;
px[i] = ((double) ran2(idum) - .5) * 2 * p0;
py[i] = ((double) ran2(idum) - .5) * 2 * p0;
}
return;
}
void
kinetic(long n, double *x, double *y, double *kint)
{
long i;
for (i = 0; i < n; i++) {
kint[i] = (x[i] * x[i]) + (y[i] * y[i]);
}
return;
}
int
main()
{
long i, n;
long seed, idum;
double *rx, *ry;
double *px, *py;
double L, p0;
double *kint;
n = 1000;
L = 2.0;
p0 = 1.22;
seed = 10;
idum = -seed;
FILE *init = fopen("initialPosition.dat", "w");
rx = (double *) malloc((double) n * sizeof(double));
ry = (double *) malloc((double) n * sizeof(double));
px = (double *) malloc((double) n * sizeof(double));
py = (double *) malloc((double) n * sizeof(double));
kint = (double *) malloc((double) n * sizeof(double));
UniformBox(n, &idum, L, p0, rx, ry, px, py);
kinetic(n, px, py, kint);
for (i = 0; i < n; i++) {
printf("%lf\t%lf\t%lf\t%lf\t%lf\n", rx[i], ry[i], px[i], py[i], kint[i]);
fprintf(init, "%lf\t%lf\t%lf\t%lf\n", rx[i], ry[i], px[i], py[i]);
}
fclose(init);
free(rx);
free(ry);
free(px);
free(py);
return 0;
}
In C , you must pass arrays into a function by reference. Thus, your function header should be
void kinetic(long n, double x, double y, double * kint);
You could also use the [] notation like is suggested in the comments.

Three Dimensional array of structs in C

Hello I am struggling to find a solution Ive defined the following 3D array of structures.
typedef struct{
float x;
float y;
float z;
} Point;
Point ***Qw;
Qw = malloc(num_bezier * sizeof(Point **));
for(i=0; i<num_bezier; i++){
Qw[i] = malloc((m+1) * sizeof(Point *));
for(j=0; j<=m;j++)
Qw[i][j] = malloc((p+1) * sizeof(Point));
}
I can loop through the array to print its contents but at some point of the program after modifying some of the elements, Im no longer able to access some of the structs in the array and i get a segfault. Any help appreciated, thanks.
PD: Ive just noticed i had defined incorrectly my struct...
typedef struct{
double x;
double y;
float z;
} Point;
As soon as i exchanged the double for float type it fixed the segfault... still trying to figure out why it was segfaulting
Consider allocating a single buffer (with pow( num_bezier, 3) elements) instead of allocating rows, columns and cells separately. That way you can avoid excess allocation but also memory fragmentation.
struct Point { float x, y, z; }
size_t bufferLength;
size_t bufferSquareLength;
struct Point* buffer; // pointer to a dynamically-allocated cubic buffer of Point values, stored in row x, column y, and depth z order.
void allocateBuffer(size_t squareLength) {
bufferSquareLength = squareLength;
bufferLength = squareLength * squareLength * squareLength;
buffer = calloc( bufferLength, sizeof(struct Point) );
}
struct Point* getElement(size_t x, size_t y, size_t z) {
Point* p = buffer + ( x * bufferSquareLength * bufferSquareLength ) + ( y * bufferSquareLength ) + z;
return p;
}
Much simpler and easier to follow.
To iterate over each value:
void forEachPoint( void(*callback(size_t x, size_t y, size_t z, struct Point* value) ) {
for(size_t x = 0; x < bufferSquareLength; x++) {
for(size_t y = 0; y < bufferSquareLength; y++) {
for(size_t z = 0; z < bufferSquareLength; z++) {
callback( x, y, z, getElement( x, y, z ) );
}
}
}
}
Simply call forEachPoint with a custom callbakc function to iterate over each struct Point value.

How to fix the holes in this console rotation animation

I have a square rotating in the console, but I get some holes. How can I fill it correctly?
#include <stdio.h>
#include <Windows.h>
#include <math.h>
void moveTo (int x, int y)
{
COORD coord = { x, y };
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
double round (double number)
{
return number < 0.0 ? ceil(number - 0.5) : floor(number + 0.5);
}
double deg2rad (double a)
{
double pi = 3.14159265358979323846;
return a * pi / 180.0;
}
int main ()
{
int w = 8;
int h = 8;
int cx = 20;
int cy = 10;
double a = 0;
while (1)
{
system("cls");
for (int y = 0; y < h; y++)
{
for (int x = 0; x < w; x++)
{
double xx = x - 4;
double yy = y - 4;
double fx = xx * cos(a) - yy * sin(a);
double fy = xx * sin(a) + yy * cos(a);
int ix = cx + round(fx);
int iy = cy + round(fy);
moveTo(ix, iy);
printf("X");
}
}
a += deg2rad(15.0);
Sleep(100);
}
return 0;
}
Not an actual answer
Aparently your code will always print the same number of X in the screen, even though this might not be always the case.
I think you shouldn't be recalculating the positions of each predefinedX but instead calculate the geometry of the lines around the square and fill the space between with Xs, as many as necessary until it hit the opposite border or something.
An alternative solution could be doubling the "density" of your square:
int w = 8*2;
int h = 8*2;
int cx = 20*2;
int cy = 10*2;
...
moveTo(ix/2, iy/2);
This should double print some dots, but should also fill gaps.

Golden Section Routine Segmentation Fault

I'm trying to find minimum point of Gamma function by Golden Section method. But when I execute the program I get segmentation fault error. I think since I'm a newbie C user, the problem may be due to calling the function Min_Search_Golden_Section wrong. Here is my complete code. I can't find my mistake. Thanks in advance.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#define A 12
#define sqrt5 2.236067977499789696
static int Stopping_Rule(double x0, double x1, double tolerance);
double sp_gamma(double z)
{
const int a = A;
static double c_space[A];
static double *c = NULL;
int k;
double accm;
if ( c == NULL ) {
double k1_factrl = 1.0; /* (k - 1)!*(-1)^k with 0!==1*/
c = c_space;
c[0] = sqrt(2.0*M_PI);
for(k=1; k < a; k++) {
c[k] = exp(a-k) * pow(a-k, k-0.5) / k1_factrl;
k1_factrl *= -k;
}
}
accm = c[0];
for(k=1; k < a; k++) {
accm += c[k] / ( z + k );
}
accm *= exp(-(z+a)) * pow(z+a, z+0.5); /* Gamma(z+1) */
return accm/z;
}
void Min_Search_Golden_Section( double (*f)(double), double* a, double *fa,
double* b, double* fb, double tolerance)
{
static const double lambda = 0.5 * (sqrt5 - 1.0);
static const double mu = 0.5 * (3.0 - sqrt5); // = 1 - lambda
double x1;
double x2;
double fx1;
double fx2;
// Find first two internal points and evaluate
// the function at the two internal points.
x1 = *b - lambda * (*b - *a);
x2 = *a + lambda * (*b - *a);
fx1 = f(x1);
fx2 = f(x2);
// Verify that the tolerance is an acceptable number
if (tolerance <= 0.0) tolerance = sqrt(DBL_EPSILON) * (*b - *a);
// Loop by exluding segments from current endpoints a, b
// to current internal points x1, x2 and then calculating
// a new internal point until the length of the interval
// is less than or equal to the tolerance.
while ( ! Stopping_Rule( *a, *b, tolerance) ) {
if (fx1 > fx2) {
*a = x1;
*fa = fx1;
if ( Stopping_Rule( *a, *b, tolerance) ) break;
x1 = x2;
fx1 = fx2;
x2 = *b - mu * (*b - *a);
fx2 = f(x2);
} else {
*b = x2;
*fb = fx2;
if ( Stopping_Rule( *a, *b, tolerance) ) break;
x2 = x1;
fx2 = fx1;
x1 = *a + mu * (*b - *a);
fx1 = f(x1);
}
}
return;
}
int main()
{
double x;
double a = 0.0, b = 4.0, fa = 0.00001, fb = 6.0;
double fx = sp_gamma(x);
Min_Search_Golden_Section( &fx, &a, &fa, &b, &fb, 0.0000001);
return 0;
}
static int Stopping_Rule(double x0, double x1, double tolerance)
{
double xm = 0.5 * fabs( x1 + x0 );
if ( xm <= 1.0 ) return ( fabs( x1 - x0 ) < tolerance ) ? 1 : 0;
return ( fabs( x1 - x0 ) < tolerance * xm ) ? 1 : 0;
}
You should be getting a compiler error. The first argument to Min_Search_Golden_Section should be a function pointer, but you pass the address of a variable instead.
When you get compiler errors, fix them - don't run the program and hope. :)
I guess you just meant to write:
Min_Search_Golden_Section( &sp_gamma, &a, &fa, &b, &fb, 0.0000001);

Resources