From 01367af99c7ab95507974ce2a035b2d500642dac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mario=20H=C3=BCttel?= Date: Sat, 28 Jul 2018 10:37:00 +0200 Subject: [PATCH] vector operations added --- trigonometric/vector-operations.c | 85 +++++++++++++++++++++++++++++++ trigonometric/vector-operations.h | 10 ++++ 2 files changed, 95 insertions(+) diff --git a/trigonometric/vector-operations.c b/trigonometric/vector-operations.c index b164471..f9e110d 100644 --- a/trigonometric/vector-operations.c +++ b/trigonometric/vector-operations.c @@ -24,3 +24,88 @@ */ #include "vector-operations.h" +#include +#include + +double vector_2d_scalar_multipy(struct vector_2d *a, struct vector_2d *b) +{ + if (a && b) + return (a->x * b->x) + (a->y * b->y); + else + return 0.0; +} + +void vector_2d_normaize(struct vector_2d *vec) +{ + double len; + if (!vec) + return; + len = sqrt(pow(vec->x,2)+pow(vec->y,2)); + vec->x = vec->x/len; + vec->y = vec->y/len; +} + +void vector_2d_rotate(struct vector_2d *vec, double angle) +{ + double sin_val, cos_val; + struct vector_2d temp; + + sin_val = sin(angle); + cos_val = cos(angle); + + vecor_2d_copy(&temp, vec); + + /* Apply rotation matrix */ + vec->x = (cos_val * temp.x) - (sin_val * temp.y); + vec->y = (sin_val * temp.x) + (cos_val * temp.y); +} + +struct vector_2d *vecor_2d_copy(struct vector_2d *opt_res, struct vector_2d *vec) +{ + struct vector_2d *res; + + if (!vec) + return NULL; + if (opt_res) { + opt_res->x = vec->x; + opt_res->y = vec->y; + return opt_res; + } else { + res = vector_2d_alloc(); + if (res) { + res->x = vec->x; + res->y = vec->y; + } + return res; + } +} + +struct vector_2d *vector_2d_alloc(void) +{ + return (struct vector_2d *)malloc(sizeof(struct vector_2d)); +} + +void vector_2d_free(struct vector_2d *vec) +{ + if (vec) { + free(vec); + } +} + +void vector_2d_scale(struct vector_2d *vec, double scale) +{ + if (!vec) + return; + + vec->x *= scale; + vec->y *= scale; +} + +double vector_2d_abs(struct vector_2d *vec) +{ + double len = 0.0; + if (vec) { + len = sqrt(pow(vec->x,2)+pow(vec->y,2)); + } + return len; +} diff --git a/trigonometric/vector-operations.h b/trigonometric/vector-operations.h index a89bc4f..59bfae5 100644 --- a/trigonometric/vector-operations.h +++ b/trigonometric/vector-operations.h @@ -31,4 +31,14 @@ struct vector_2d { double y; }; + +double vector_2d_scalar_multipy(struct vector_2d *a, struct vector_2d *b); +void vector_2d_normalize(struct vector_2d *vec); +void vecor_2d_rotate(struct vector_2d *vec, double angle); +struct vector_2d *vecor_2d_copy(struct vector_2d *opt_res, struct vector_2d *vec); +struct vector_2d *vector_2d_alloc(void); +void vector_2d_free(struct vector_2d *vec); +void vector_2d_scale(struct vector_2d *vec, double scale); +double vector_2d_abs(struct vector_2d *vec); + #endif /* _VECTOR_OPERATIONS_H_ */