8000 define abs for int, float and complex number · runtimehub-com/algorithms-mojo@c5c8722 · GitHub
[go: up one dir, main page]

Skip to content

Commit c5c8722

Browse files
committed
define abs for int, float and complex number
1 parent e55ba28 commit c5c8722

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

.gitignore

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# for PyCharm
2+
.idea/
3+
4+
# for Mac
5+
.DS_Store

maths/abs.mojo

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
## Absolute Value
2+
##
3+
## The absolute value of a number is the number without its sign.
4+
5+
6+
struct complext:
7+
var real: Int
8+
var imag: Int
9+
10+
11+
fn __init__(inout self: Self, real: Int, imag: Int):
12+
self.real = real
13+
self.imag = imag
14+
15+
struct Math:
16+
@staticmethod
17+
fn abs(n: Int) -> Int:
18+
## Returns the absolute value of an integer.
19+
## >>> Math.abs(-5)
20+
## 5
21+
## >>> Math.abs(5)
22+
## 5
23+
return n if n >= 0 else -n
24+
25+
@staticmethod
26+
fn abs(n: FloatLiteral) -> Int:
27+
## Returns the absolute value of a float.
28+
## >>> Math.abs(-5.5)
29+
## 5.5
30+
## >>> Math.abs(5.5)
31+
## 5.5
32+
return n if n >= 0 else -n
33+
34+
35+
## For a complex number z = x + yi,
36+
## we define the absolute value |z| as being the distance from z to 0 in the complex plane C.
37+
## Reference: https://www2.clarku.edu/faculty/djoyce/complex/abs.html#:~:text=For%20a%20complex%20number%20z,on%20the%20real%20number%20line.
38+
@staticmethod
39+
fn abs(n: complext) -> FloatLiteral:
40+
## Returns the absolute value of a complex number.
41+
## >>> Math.abs(complext(5, 0))
42+
## 5.0
43+
## >>> Math.abs(complext(3, 4))
44+
## 5.0
45+
return math.sqrt(n.real ** 2 + n.imag ** 2)

0 commit comments

Comments
 (0)
0