From 14199e0590cf07f791c7422ee0b670d93ff0c5b0 Mon Sep 17 00:00:00 2001 From: Yukti Khosla <44090430+Yukti-09@users.noreply.github.com> Date: Sat, 15 Aug 2020 21:49:33 +0530 Subject: [PATCH] Create Transformations2D.py (#2310) * Create Transformations2D.py * Update Transformations2D.py * Drop numpy and add type hints and doctests * Rename Transformations2D.py to transformations_2d.py Co-authored-by: Christian Clauss --- linear_algebra/src/transformations_2d.py | 62 ++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 linear_algebra/src/transformations_2d.py diff --git a/linear_algebra/src/transformations_2d.py b/linear_algebra/src/transformations_2d.py new file mode 100644 index 000000000..9ee238fd7 --- /dev/null +++ b/linear_algebra/src/transformations_2d.py @@ -0,0 +1,62 @@ +""" +2D Transformations are regularly used in Linear Algebra. + +I have added the codes for reflection, projection, scaling and rotation 2D matrices. + + scaling(5) = [[5.0, 0.0], [0.0, 5.0]] + rotation(45) = [[0.5253219888177297, -0.8509035245341184], + [0.8509035245341184, 0.5253219888177297]] +projection(45) = [[0.27596319193541496, 0.446998331800279], + [0.446998331800279, 0.7240368080645851]] +reflection(45) = [[0.05064397763545947, 0.893996663600558], + [0.893996663600558, 0.7018070490682369]] +""" +from math import cos, sin +from typing import List + + +def scaling(scaling_factor: float) -> List[List[float]]: + """ + >>> scaling(5) + [[5.0, 0.0], [0.0, 5.0]] + """ + scaling_factor = float(scaling_factor) + return [[scaling_factor * int(x == y) for x in range(2)] for y in range(2)] + + +def rotation(angle: float) -> List[List[float]]: + """ + >>> rotation(45) # doctest: +NORMALIZE_WHITESPACE + [[0.5253219888177297, -0.8509035245341184], + [0.8509035245341184, 0.5253219888177297]] + """ + c, s = cos(angle), sin(angle) + return [[c, -s], [s, c]] + + +def projection(angle: float) -> List[List[float]]: + """ + >>> projection(45) # doctest: +NORMALIZE_WHITESPACE + [[0.27596319193541496, 0.446998331800279], + [0.446998331800279, 0.7240368080645851]] + """ + c, s = cos(angle), sin(angle) + cs = c * s + return [[c * c, cs], [cs, s * s]] + + +def reflection(angle: float) -> List[List[float]]: + """ + >>> reflection(45) # doctest: +NORMALIZE_WHITESPACE + [[0.05064397763545947, 0.893996663600558], + [0.893996663600558, 0.7018070490682369]] + """ + c, s = cos(angle), sin(angle) + cs = c * s + return [[2 * c - 1, 2 * cs], [2 * cs, 2 * s - 1]] + + +print(f" {scaling(5) = }") +print(f" {rotation(45) = }") +print(f"{projection(45) = }") +print(f"{reflection(45) = }")