c-uebungen/Assignment_023/solution/vector_stack.c

101 lines
2.4 KiB
C

#include <stdlib.h>
#include <math.h>
#include <stdio.h>
#include "vector_stack.h"
void vec_init(Vector* result, double x, double y, double z) {
result->x = x;
result->y = y;
result->z = z;
}
void vec_null(Vector* result) {
vec_init(result, 0.0, 0.0, 0.0);
}
void vec_mul_scalar(Vector* result, Vector v, double scalar) {
vec_init(result, v.x * scalar,
v.y * scalar,
v.z * scalar);
}
double vec_mul_dot(Vector first, Vector second) {
return first.x * second.x +
first.y * second.y +
first.z * second.z;
}
void vec_mul_cross(Vector* result, Vector first, Vector second) {
return vec_init(result, first.y * second.z - first.z * second.y,
first.z * second.x - first.x * second.z,
first.x * second.y - first.y * second.x);
}
void vec_add(Vector* result, Vector first, Vector second) {
return vec_init(result, first.x + second.x,
first.y + second.y,
first.z + second.z);
}
void vec_sub(Vector* result, Vector first, Vector second) {
return vec_init(result, first.x - second.x,
first.y - second.y,
first.z - second.z);
}
int vec_equals(Vector first, Vector second) {
return (first.x == second.x)
&& (first.y == second.y)
&& (first.z == second.z);
}
static const int MAX_LENGTH=128;
char* vec_to_str(Vector v) {
char* result = (char*) malloc(MAX_LENGTH);
if (!result) {
return NULL;
}
snprintf(result, MAX_LENGTH, "[ %.2f %.2f %.2f ]", v.x, v.y, v.z);
return result;
}
void vec_print(Vector v) {
char* str = vec_to_str(v);
printf("%s", str);
free(str);
}
double vec_length(Vector v) {
return sqrt(v.x * v.x
+ v.y * v.y
+ v.z * v.z);
}
int vec_norm(Vector* result, Vector v) {
double length = vec_length(v);
if (length == 0.0) {
/* no norm for a null vector */
return -1;
}
vec_init(result, v.x / length,
v.y / length,
v.z / length);
return 0;
}
int vec_collinear(Vector first, Vector second) {
Vector cross, nullVector;
vec_mul_cross(&cross, first, second);
vec_null(&nullVector);
int result = vec_equals(nullVector, cross);
return result;
}