From e89fb7b93fd5f1042f05107e51fea85f51499668 Mon Sep 17 00:00:00 2001 From: Nao Pross Date: Sun, 9 Dec 2018 19:51:20 +0100 Subject: Add vector example documentation --- vector/vector.c | 107 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 vector/vector.c (limited to 'vector/vector.c') diff --git a/vector/vector.c b/vector/vector.c new file mode 100644 index 0000000..c8a5906 --- /dev/null +++ b/vector/vector.c @@ -0,0 +1,107 @@ +#include +#include + +struct vec3 { + double x; + double y; + double z; +}; + +struct vec3 vec3_add(struct vec3 * const v, struct vec3 * const u) +{ + struct vec3 result = {0, 0, 0}; + + if (v == NULL || u == NULL) + return result; + + result.x = v->x + u->x; + result.y = v->y + u->y; + result.z = v->z + u->z; + + return result; +} + +struct vec3 vec3_mul(struct vec3 * const v, const double scalar) +{ + struct vec3 result = {0, 0, 0}; + + if (v == NULL) + return result; + + result.x = scalar * v->x; + result.y = scalar * v->y; + result.z = scalar * v->z; + + return result; +} + +struct vec3 vec3_sub(struct vec3 * const v, struct vec3 * const u) +{ + struct vec3 result = {0, 0, 0}; + + result = vec3_mul(u, -1.0); + result = vec3_add(v, &result); + + return result; +} + +double vec3_dot(struct vec3 * const v, struct vec3 * const u) +{ + if (v == NULL || u == NULL) + return 0; + + return (v->x * u->x) + (v->y * u->y) + (v->z * u->y); +} + +struct vec3 vec3_cross(struct vec3 * const v, struct vec3 * const u) +{ + struct vec3 result = {0, 0, 0}; + + result.x = (v->y * u->z) - (v->z * u->y); + result.y = (v->z * u->x) - (v->x * u->z); + result.z = (v->x * u->y) - (v->y * u->x); + + return result; +} + +void vec3_print(struct vec3 * const v) +{ + if (v == NULL) + return; + + printf("<%.2f,%.2f,%.2f>\n", v->x, v->y, v->y); +} + + +int main(int argc, char *argv[]) +{ + struct vec3 a = {1, 2, 3}; + struct vec3 b = {4, 5, 6}; + struct vec3 res; + + printf("a = "); + vec3_print(&a); + printf("b = "); + vec3_print(&b); + + printf("sum a + b : "); + res = vec3_add(&a, &b); + vec3_print(&res); + + printf("sub a - b : "); + res = vec3_sub(&a, &b); + vec3_print(&res); + + printf("product 3*a : "); + res = vec3_mul(&a, 3); + vec3_print(&res); + + printf("dot product : "); + printf("%.2f\n", vec3_dot(&a, &b)); + + printf("cross product : "); + res = vec3_cross(&a, &b); + vec3_print(&res); + + return 0; +} -- cgit v1.2.1