-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValue.swift
More file actions
103 lines (85 loc) · 2.71 KB
/
Value.swift
File metadata and controls
103 lines (85 loc) · 2.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
//
// Value.swift
// PhysicsSystem
//
// Created by Andrew Fox on 12/3/22.
//
import Foundation
struct value : Equatable {
let base: Decimal
let power: Int
let added_value: Decimal
init(_ base: Decimal = 1.0, _ power: Int = 0, added_value: Decimal = 0.0) {
var base: Decimal = base
var power: Int = power
while abs(base) >= 10.0 {
base /= 10.0
power += 1
}
while abs(base) < 1.0 && base != 0.0 {
base *= 10.0
power -= 1
}
self.base = base
self.power = power
self.added_value = added_value
}
init(_ str: String) {
let comps = str.components(separatedBy: "E")
let l: Decimal
let r: Int
if comps.count >= 1 {
l = Decimal(string: comps[0]) ?? 1.0
} else {
l = 1.0
}
if comps.count >= 2 {
r = Int(comps[1]) ?? 0
} else {
r = 0
}
self.init(l, r)
}
func toString() -> String {
return String(describing: base) + "E" + String(power)
}
static func * (left: value, right: value) -> value {
value((left.base + right.added_value) * right.base, left.power + right.power)
}
static func / (left: value, right: value) -> value {
value((left.base - right.added_value) / right.base, left.power - right.power)
}
static func *= (left: inout value, right: value) {
left = left * right
}
static func /= (left: inout value, right: value) {
left = left / right
}
static func == (left: value, right: value) -> Bool {
return left.base == right.base && left.power == right.power && left.added_value == right.added_value
}
}
struct Value : Hashable {
let variable: Variable.Type
var numericValue: value
var units: Unit
init(_ variable: Variable.Type, _ numericValue: value, _ units: Unit) {
self.variable = variable
self.numericValue = numericValue * units.si_base_factor
self.units = units
}
mutating func update(_ numericValue: value, _ units: Unit) {
self.numericValue = numericValue * (units.si_base_factor / self.units.si_base_factor)
self.units = units
}
func copy() -> Value {
return Value(variable, numericValue, units)
}
static func == (lhs: Value, rhs: Value) -> Bool {
return lhs.variable == rhs.variable && lhs.numericValue == rhs.numericValue && lhs.units == rhs.units
}
func hash(into hasher: inout Hasher) {
hasher.combine(variable.symbol)
hasher.combine(numericValue.base * pow(10, numericValue.power))
}
}