2進数、連立方程式

ruby
math
code
Author

geeknees

Published

July 30, 2023

2進数

def decimal_to_binary(target)
  remainders = []   # List to store remainders

  # Until the quotient becomes 0 during division
  while target != 0
    remainders << target % 2   # Remainder
    target = target / 2   # Quotient
  end

  remainders.reverse()   # Reverse the elements in the list
end
:decimal_to_binary
p decimal_to_binary(65)
[1, 0, 0, 0, 0, 0, 1]
[1, 0, 0, 0, 0, 0, 1]
def binary_to_decial(target)
  raise ArgumentError if target.to_s =~ /[^01]/
  target
    .digits
    .each_with_index
    .sum { |digit, index| digit * 2**index }
end
:binary_to_decial
p binary_to_decial(1001)
9
9

連立方程式

require "charty"
require "datasets"
require "numo/narray"
false
charty = Charty::Plotter.new()
#<Charty::Plotter:0x00000001206c2458 @backend=#<Charty::Backends::Gruff:0x0000000121247a58 @plot=Gruff>>

\[ y = -2/3 x + 6 \] \[ y = 1/2 x + 2 \]

scatter = charty.scatter do
  series -10..10, (-10..10).map{|x| x/2.to_f * -3 + 6 }, 'sample1'
  series -10..10, (-10..10).map{|x| (x/2.to_f) + 2 }, 'sample2'
  range -10..10, -10..10
  xlabel 'x'
  ylabel 'y'
end
scatter.render("sample_images/1.png")

\[ 2/3 x + y = 6 \] \[ -1/2 x + y = 2 \]

require 'matrix'

a = Matrix[[2/3.to_f, 1],[-1/2.to_f, 1]]
b = Vector[6,2]
a.lup.solve(b)
Vector[3.4285714285714284, 3.7142857142857144]

\[ y = - 1/2x + 1/2 \] \[ y = -1/3 x \]

scatter = charty.scatter do
  series -10..10, (-10..10).map{|x| x/-2.to_f + 1/2.to_f }, 'sample1'
  series -10..10, (-10..10).map{|x| (x/-3.to_f)}, 'sample2'
  range -10..10, -10..10
  xlabel 'x'
  ylabel 'y'
end
scatter.render("sample_images/2.png")

\[ x + 2y = 1 \] \[ x + 3y = 0 \]

require 'matrix'

a = Matrix[[1.0, 2.0],[1.0, 3.0]]
b = Vector[1.0, 0.0]
a.lup.solve(b)
Vector[3.0, -1.0]

\[ x = 3, y = -1 \]


\(2x + 4y - 2z = 4\)

\(2x + y + z = 7\)

\(x + y + z = 6\)

require 'matrix'

a = Matrix[[2, 4, -2],[2, 1, 1],[1, 1, 1]]
b = Vector[4,7,6]
a.lup.solve(b)
Vector[(1/1), (2/1), (3/1)]

\[ x = 1, y = 2, z = 3 \]