module Silicium::Algebra
Algebra
module helps to perform calculations with polynoms
Attributes
Public Instance Methods
Checks if new variable is present and is not the same as last known variable
# File lib/algebra.rb, line 85 def another_variable?(old_variable, new_variable) !new_variable.nil? && old_variable != new_variable end
+eratosthen_primes_to(n)+ finds all primes up to n with the sieve of eratosthenes
eratosthen_primes_to(1) # => [] eratosthen_primes_to(15) # => [2, 3, 5, 7, 11, 13] eratosthen_primes_to(50) # => [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
# File lib/algebra.rb, line 25 def eratosthen_primes_to(n) raise ArgumentError unless valid_n?(n) array = (2..n).to_a array.each do |prime| square = prime**2 break if square > n array -= square.step(n, prime).to_a end array end
+evaluate(val)+ counts the result using a given value
# File lib/algebra.rb, line 111 def evaluate(val) res = to_ruby_s(val) eval(res) end
@param [String] expr - part of analytical function that has one independent variable @return [Array] retuns pair, the first value indicates if parsing succeeded, the second is variable
# File lib/algebra.rb, line 78 def extract_variable(expr) expr[/(\s?\d*\s?\*\s?)?([a-z])(\^\d*)?|\s?\d+$/] [!Regexp.last_match.nil?, Regexp.last_match(2)] end
+initializer(str)+ creates a correct ruby str from given one
# File lib/algebra.rb, line 13 def initializer(str) raise PolynomError, 'Invalid string for polynom ' unless polycop(str) @str = str end
check for extra letters in term
# File lib/algebra.rb, line 90 def letter_controller(term) allowed_w = %w[ln lg log cos sin] letters = term.scan(/[a-z]{2,}/) letters = letters.join letters.empty? || allowed_w.include?(letters) end
+polycop(str)+ determines whether the str is an appropriate function which only has one variable
polycop('x^2 + 2 * x + 7') # => True polycop('x^2 +2nbbbbb * x + 7') # => False
# File lib/algebra.rb, line 53 def polycop(str) @letter_var = nil parsed = str.split(/[-+]/) parsed.each { |term| return false unless valid_term?(term) } true end
+to_ruby_s(val)+ transforms @str into a correct ruby str works for logarithms, trigonometry and misspelled power
to_ruby_s('') # =>
# File lib/algebra.rb, line 102 def to_ruby_s(val) temp_str = @str temp_str.gsub!('^', '**') temp_str.gsub!(/lg|log|ln/, 'Math::\1') temp_str.gsub!(@letter_var, val) temp_str end
Checks if the number n is correct
# File lib/algebra.rb, line 40 def valid_n?(n) return false if n <= 0 return false unless n.class == Integer true end
Parses single polynomial term and returns false if term is incorrect on has different independent variable It updated current independent variable if it wasn't set before
# File lib/algebra.rb, line 65 def valid_term?(term) correct, cur_var = extract_variable(term) return false unless correct @letter_var ||= cur_var !(another_variable?(@letter_var, cur_var) || !letter_controller(term)) end