math_expression 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,17 @@
1
+ *.gem
2
+ *.rbc
3
+ .bundle
4
+ .config
5
+ .yardoc
6
+ Gemfile.lock
7
+ InstalledFiles
8
+ _yardoc
9
+ coverage
10
+ doc/
11
+ lib/bundler/man
12
+ pkg
13
+ rdoc
14
+ spec/reports
15
+ test/tmp
16
+ test/version_tmp
17
+ tmp
@@ -0,0 +1,23 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'Expression/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "math_expression"
8
+ spec.version = Expression::VERSION
9
+ spec.authors = ["mhmd689"]
10
+ spec.email = ["b689d8@gmail.com"]
11
+ spec.description = %q{Mathmatical expression calculator}
12
+ spec.summary = %q{The gem evaluates mathmatical expressions provided as a string}
13
+ spec.homepage = ""
14
+ spec.license = "MIT"
15
+
16
+ spec.files = `git ls-files`.split($/)
17
+ spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
18
+ spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
19
+ spec.require_paths = ["lib"]
20
+
21
+ spec.add_development_dependency "bundler", "~> 1.3"
22
+ spec.add_development_dependency "rake"
23
+ end
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in Expression.gemspec
4
+ gemspec
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2015 mhmd689
2
+
3
+ MIT License
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ "Software"), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,36 @@
1
+ # Expression
2
+
3
+ Mathematical expression calculator. Use this gem as a calculator.
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ gem 'Expression'
10
+
11
+ And then execute:
12
+
13
+ $ bundle
14
+
15
+ Or install it yourself as:
16
+
17
+ $ gem install Expression
18
+
19
+ ## Usage
20
+
21
+ Initialize a variable:
22
+
23
+ some_var = MathExpression.new
24
+
25
+ and then it is just:
26
+
27
+ some_var.eval(Your_expression)
28
+
29
+
30
+ ## Contributing
31
+
32
+ 1. Fork it
33
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
34
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
35
+ 4. Push to the branch (`git push origin my-new-feature`)
36
+ 5. Create new Pull Request
@@ -0,0 +1,9 @@
1
+ require "bundler/gem_tasks"
2
+ require "rake/testtask"
3
+ Rake::TestTask.new do |t|
4
+ t.libs << "lib"
5
+ t.libs << "test"
6
+ t.test_files = FileList['test/test*']
7
+ t.verbose = false
8
+ end
9
+ task :default => :test
@@ -0,0 +1,6 @@
1
+ require "Expression/version"
2
+ require "Expression/parser"
3
+
4
+ module Expression
5
+ # Your code goes here...
6
+ end
@@ -0,0 +1,35 @@
1
+ class MathExpression
2
+ private
3
+
4
+ def get_char
5
+ @look = @input.shift
6
+ end
7
+
8
+ def get_number
9
+ value = 0
10
+ nb_decimals = false
11
+ expected('integer') if (!digit?(@look) && @look != '.')
12
+ while (digit?(@look) || @look == '.')
13
+ if @look == '.'
14
+ match '.'
15
+ if nb_decimals
16
+ expected "integer"
17
+ end
18
+ nb_decimals = 1
19
+ else
20
+ if nb_decimals
21
+ nb_decimals *= 10
22
+ value = value + @look.to_f / nb_decimals
23
+ get_char
24
+ skip_white
25
+ else
26
+ value = 10 * value + @look.to_i
27
+ get_char
28
+ skip_white
29
+ end
30
+ end
31
+ end
32
+ value
33
+ end
34
+
35
+ end
@@ -0,0 +1,153 @@
1
+ class MathExpression
2
+ private
3
+
4
+ def addop?(x)
5
+ ['+', '-'].include? x
6
+ end
7
+
8
+ def digit?(x)
9
+ [*(0..9)].map(&:to_s).include?(x)
10
+ end
11
+
12
+ def alpha?(x)
13
+ [*('a'..'z')].include? x
14
+ end
15
+
16
+ def match(char)
17
+ if @look == char
18
+ get_char
19
+ skip_white
20
+ else
21
+ expected(char)
22
+ end
23
+ end
24
+
25
+ def match_all(string)
26
+ string.each_char { |x| match(x) }
27
+ end
28
+
29
+ def skip_white
30
+ while @look =~ /\s/
31
+ get_char
32
+ end
33
+ end
34
+ def trig
35
+ case @look
36
+ when 'c'
37
+ match_all('cos')
38
+ case @look
39
+ when 'h'
40
+ match_all('h(')
41
+ value = cosh(calculate)
42
+ when '('
43
+ match('(')
44
+ value = cos(calculate)
45
+ else
46
+ expected('cos() or cosh()')
47
+ end
48
+ when 's'
49
+ match('s')
50
+ if @look == 'q'
51
+ match_all('qrt(')
52
+ value = sqrt(calculate)
53
+ else
54
+ match_all('in')
55
+ case @look
56
+ when 'h'
57
+ match_all('h(')
58
+ value = sinh(calculate)
59
+ when '('
60
+ match('(')
61
+ value = sin(calculate)
62
+ else
63
+ expected('sin() or sinh()')
64
+ end
65
+ end
66
+ when 'r'
67
+ match_all('root')
68
+ base = get_number
69
+ match('(')
70
+ value = calculate ** (1.0/base)
71
+ when 't'
72
+ match_all('tan')
73
+ case @look
74
+ when 'h'
75
+ match_all('h(')
76
+ value = tanh(calculate)
77
+ when '('
78
+ match('(')
79
+ value = tan(calculate)
80
+ else
81
+ expected('tan() or tanh()')
82
+ end
83
+ when 'l'
84
+ match('l')
85
+ case @look
86
+ when 'n'
87
+ match_all('n(')
88
+ value = log(calculate)
89
+ when 'o'
90
+ match_all('og')
91
+ if digit? @look
92
+ base = get_number
93
+ elsif @look == "("
94
+ base = 10
95
+ else
96
+ expected("integer or ( ")
97
+ end
98
+ match('(')
99
+ value = log(calculate, base)
100
+ else
101
+ expected('ln() or log()')
102
+ end
103
+ when 'e'
104
+ match_all('exp(')
105
+ value = exp(calculate)
106
+ when 'a'
107
+ match_all('arc')
108
+ case @look
109
+ when 'c'
110
+ match_all('cos')
111
+ case @look
112
+ when 'h'
113
+ match_all('h(')
114
+ value = acosh(calculate)
115
+ when '('
116
+ match('(')
117
+ value = acos(calculate)
118
+ else
119
+ expected('arccos() or arccosh()')
120
+ end
121
+ when 's'
122
+ match_all('sin')
123
+ case @look
124
+ when 'h'
125
+ match_all('h(')
126
+ value = asinh(calculate)
127
+ when '('
128
+ match('(')
129
+ value = asin(calculate)
130
+ else
131
+ expected('arcsin() or arcsinh()')
132
+ end
133
+ when 't'
134
+ match_all('tan')
135
+ case @look
136
+ when 'h'
137
+ match_all('h(')
138
+ value = atanh(calculate)
139
+ when '('
140
+ match('(')
141
+ value = atan(calculate)
142
+ else
143
+ expected('arctan() or arctanh()')
144
+ end
145
+ end
146
+ else
147
+ raise InvalidInput, "unexpected input: \"#{@look}\""
148
+ end
149
+ match(')')
150
+ value
151
+ end
152
+
153
+ end
@@ -0,0 +1,120 @@
1
+ #!/usr/bin/env ruby -wKU
2
+ include Math
3
+ %w(getters identifiers).each {|x| require_relative x }
4
+
5
+ class InvalidInput < Exception; end
6
+ class IndeterminedForm < Exception; end
7
+
8
+ class MathExpression
9
+ def initialize()
10
+ @input = nil
11
+ @look = nil
12
+ end
13
+
14
+ def eval(input)
15
+ @input = input
16
+ init
17
+ temp = calculate
18
+ unless @look.nil?
19
+ raise InvalidInput, "unexpected input: \"#{@look}\""
20
+ end
21
+ temp
22
+ end
23
+
24
+
25
+ private
26
+
27
+ def expected(msg)
28
+ raise InvalidInput, "\a\"#{msg}\" expected"
29
+ end
30
+
31
+ def factor
32
+
33
+ if @look == '('
34
+ match('(')
35
+ value = calculate
36
+ match(')')
37
+ elsif @look == '['
38
+ match('[')
39
+ value = calculate
40
+ match(']')
41
+ elsif alpha? @look
42
+ value = trig
43
+ else
44
+ value = get_number
45
+ end
46
+ value
47
+ end
48
+
49
+ def calculate
50
+ if addop? @look
51
+ value = 0
52
+ else
53
+ value = term
54
+ end
55
+ while addop?(@look)
56
+ case @look
57
+ when '+'
58
+ match('+')
59
+ value += term
60
+ when '-'
61
+ match('-')
62
+ value -= term
63
+ end
64
+ end
65
+ value
66
+ end
67
+
68
+ def ident
69
+ value = factor
70
+ while %w{! % ^}.include? @look
71
+ case @look
72
+ when '^'
73
+ match('^')
74
+ value **= factor
75
+ when '%'
76
+ match '%'
77
+ value = value % factor
78
+ when '!'
79
+ match('!')
80
+ str = value.to_s.split(".")
81
+ if str[1] == "0" || str.size == 1
82
+ temp = (1..value).reduce(1, :*)
83
+ value = temp
84
+ else
85
+ raise InvalidInput, "Factorial is not defined for floats"
86
+ end
87
+ end
88
+ end
89
+ value
90
+ end
91
+
92
+ def term
93
+ value = ident
94
+ while ['*', '/'].include? @look
95
+ case @look
96
+ when '*'
97
+ match('*')
98
+ value *= ident
99
+ when '/'
100
+ match('/')
101
+ numerator = value
102
+ denomenator = ident
103
+ if denomenator == 0
104
+ raise IndeterminedForm, "Division by zero is undefined"
105
+ else
106
+ value = numerator.to_f / denomenator
107
+ end
108
+ end
109
+ end
110
+ value
111
+ end
112
+
113
+ def init
114
+ @input = @input.downcase.split('')
115
+ get_char
116
+ skip_white
117
+ end
118
+ end
119
+
120
+ # puts MathExpression.new().eval(gets)
@@ -0,0 +1,3 @@
1
+ module Expression
2
+ VERSION = "0.0.1"
3
+ end
@@ -0,0 +1,89 @@
1
+ require "./lib/Expression.rb"
2
+ require "test/unit"
3
+
4
+ class TestExpression < Test::Unit::TestCase
5
+
6
+ def setup
7
+ @exp = MathExpression.new
8
+ end
9
+
10
+ def test_it_should_work_for_single_digits
11
+ assert_equal @exp.eval('3'), 3
12
+ end
13
+
14
+ def test_it_should_work_with_unary_signs
15
+ assert_equal @exp.eval('+2'), 2
16
+ assert_equal @exp.eval('-3'), -3
17
+ end
18
+
19
+ def test_it_should_work_with_floats
20
+ assert_equal @exp.eval('.5'), 0.5
21
+ assert_equal @exp.eval('0.5'), 0.5
22
+ assert_equal @exp.eval('-.045'), -0.045
23
+ end
24
+
25
+ def test_it_should_work_with_basic_arithmetic
26
+ assert_equal @exp.eval('1+1'), 2
27
+ assert_equal @exp.eval('11+1'), 12
28
+ assert_equal @exp.eval('1-1'), 0
29
+ assert_equal @exp.eval('1.1 + 2.1'), 3.2
30
+ assert_equal @exp.eval('2*3'), 6
31
+ assert_equal @exp.eval('-4/2'), -2
32
+ assert_equal @exp.eval('3/2'), 1.5
33
+ assert_equal @exp.eval('2^3'), 8
34
+ end
35
+
36
+ def test_it_should_follow_pemdas_rule
37
+ assert_equal @exp.eval('9-2*3'), 3
38
+ assert_equal @exp.eval('9+3/2'), 10.5
39
+ assert_equal @exp.eval('(9+3)/2'), 6
40
+ assert_equal @exp.eval('(9+3)/[2- 1]'), 12
41
+ assert_equal @exp.eval(' 8 - (7 - 6) + 5'), 12
42
+ assert_equal @exp.eval('9 - 6*7^(1+2)'), -2049
43
+ assert_equal @exp.eval('9^2*3'), 243
44
+
45
+ end
46
+
47
+ def test_factorial_and_modulo
48
+ assert_equal @exp.eval('5!'), 120
49
+ assert_equal @exp.eval('5! +2'), 122
50
+ assert_equal @exp.eval('(3+4)! * 2 + 1'), 10081
51
+ assert_equal @exp.eval('9 % 6'), 3
52
+ assert_raise(InvalidInput) { @exp.eval('6.43!') }
53
+ end
54
+
55
+ def test_functions
56
+ assert_equal @exp.eval('sqrt(25)'), 5
57
+ assert_raise(Math::DomainError) { @exp.eval('sqrt(-2253)') }
58
+ assert_equal @exp.eval('root3(27)'), 3
59
+ assert_equal @exp.eval('cos(0)'), 1
60
+ assert_equal @exp.eval('sin(0)'), 0
61
+ assert_equal @exp.eval('tan(0)'), 0
62
+ assert_equal @exp.eval('arccos(1)'), 0
63
+ assert_equal @exp.eval('arcsin(0)'), 0
64
+ assert_equal @exp.eval('arctan(0)'), 0
65
+ assert_in_delta @exp.eval('exp(1)'), 2.71, 0.01
66
+ assert_equal @exp.eval('ln(exp(1))'), 1
67
+ assert_equal @exp.eval('log(10)'), 1
68
+ assert_equal @exp.eval('log2(2)'), 1
69
+ assert_equal @exp.eval('arccosh(cosh(2))'), 2
70
+ assert_equal @exp.eval('arcsinh(sinh(2))'), 2
71
+ assert_in_delta @exp.eval('arctanh(tanh(2))'), 2, 0.0001
72
+ assert_in_delta @exp.eval('cosh(1)'), 1.54, 0.01
73
+ assert_in_delta @exp.eval('sinh(1)'), 1.17, 0.01
74
+ assert_in_delta @exp.eval('tanh(1)'), 0.76, 0.01
75
+ end
76
+
77
+
78
+ def test_errors
79
+ assert_raise(InvalidInput) { @exp.eval('312c5') }
80
+ assert_raise(InvalidInput) { @exp.eval('3+') }
81
+ assert_raise(InvalidInput) { @exp.eval('3^') }
82
+ assert_raise(IndeterminedForm) { @exp.eval('0/0') }
83
+ assert_raise(InvalidInput) { @exp.eval('some random stuff') }
84
+ assert_raise(InvalidInput) { @exp.eval('+') }
85
+ assert_raise(InvalidInput) { @exp.eval('root(3)') }
86
+ assert_raise(IndeterminedForm) { @exp.eval('3/0') }
87
+ end
88
+
89
+ end
metadata ADDED
@@ -0,0 +1,91 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: math_expression
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - mhmd689
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2015-09-14 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: bundler
16
+ requirement: !ruby/object:Gem::Requirement
17
+ none: false
18
+ requirements:
19
+ - - ~>
20
+ - !ruby/object:Gem::Version
21
+ version: '1.3'
22
+ type: :development
23
+ prerelease: false
24
+ version_requirements: !ruby/object:Gem::Requirement
25
+ none: false
26
+ requirements:
27
+ - - ~>
28
+ - !ruby/object:Gem::Version
29
+ version: '1.3'
30
+ - !ruby/object:Gem::Dependency
31
+ name: rake
32
+ requirement: !ruby/object:Gem::Requirement
33
+ none: false
34
+ requirements:
35
+ - - ! '>='
36
+ - !ruby/object:Gem::Version
37
+ version: '0'
38
+ type: :development
39
+ prerelease: false
40
+ version_requirements: !ruby/object:Gem::Requirement
41
+ none: false
42
+ requirements:
43
+ - - ! '>='
44
+ - !ruby/object:Gem::Version
45
+ version: '0'
46
+ description: Mathmatical expression calculator
47
+ email:
48
+ - b689d8@gmail.com
49
+ executables: []
50
+ extensions: []
51
+ extra_rdoc_files: []
52
+ files:
53
+ - .gitignore
54
+ - Expression.gemspec
55
+ - Gemfile
56
+ - LICENSE.txt
57
+ - README.md
58
+ - Rakefile
59
+ - lib/Expression.rb
60
+ - lib/Expression/getters.rb
61
+ - lib/Expression/identifiers.rb
62
+ - lib/Expression/parser.rb
63
+ - lib/Expression/version.rb
64
+ - test/test_expression.rb
65
+ homepage: ''
66
+ licenses:
67
+ - MIT
68
+ post_install_message:
69
+ rdoc_options: []
70
+ require_paths:
71
+ - lib
72
+ required_ruby_version: !ruby/object:Gem::Requirement
73
+ none: false
74
+ requirements:
75
+ - - ! '>='
76
+ - !ruby/object:Gem::Version
77
+ version: '0'
78
+ required_rubygems_version: !ruby/object:Gem::Requirement
79
+ none: false
80
+ requirements:
81
+ - - ! '>='
82
+ - !ruby/object:Gem::Version
83
+ version: '0'
84
+ requirements: []
85
+ rubyforge_project:
86
+ rubygems_version: 1.8.23
87
+ signing_key:
88
+ specification_version: 3
89
+ summary: The gem evaluates mathmatical expressions provided as a string
90
+ test_files:
91
+ - test/test_expression.rb