1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

paiza.ioでelixirAdvent Calendar 2022

Day 7

paiza.ioでelixir その82

Last updated at Posted at 2022-11-19

概要

paiza.ioでelixirやってみた。
練習問題やってみた。

練習問題

ローパスフィルターを実装せよ。

サンプルコード


defmodule Main do
    def vin(v) do
        v
		|> Enum.with_index()
		|> Enum.map(fn {x, t} ->
            (0.6 * :math.sin(t / 8000 * 2 * :math.pi * 220) + 0.5) * :math.sin(t / 8000 * 2 * :math.pi * 2000);
        end)
    end
	def lpf(v) do
	    samplerate = 8000 
	    freq = 300
	    q = 1.0
	    omega = 2.0 * :math.pi * freq / samplerate
	    alpha = :math.sin(omega) / (2.0 * q)
	    a0 = 1.0 + alpha
	    a1 = -2.0 * :math.cos(omega)
	    a2 = 1.0 - alpha
	    b0 = (1.0 - :math.cos(omega)) / 2.0
	    b1 = 1.0 - :math.cos(omega)
	    b2 = (1.0 - :math.cos(omega)) / 2.0
	    in1 = 0
	    in2 = 0
	    out1 = 0
	    out2 = 0
	    v
	    |> Enum.map(fn x -> 
		    v = b0 / a0 * x + b1 / a0 * in1 + b2 / a0 * in2 - a1 / a0 * out1 - a2 / a0 * out2
		    in2 = in1
		    in1 = x
		    out2 = out1
		    out1 = v
        end)
	end
	def main do
        IO.puts """
<html><head></head><body>
<canvas id="canvas" width="300" height="300"></canvas>
<script type="text/javascript">
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
function draw(data, n) {
	var hcenter = n * 100 + 50;
	ctx.strokeStyle = "#f0f";
	ctx.lineWidth = 2;
	ctx.moveTo(0, hcenter);
	for (var i = 1; i < canvas.width; i++) 
	{
		ctx.lineTo(i, data[i] * 30 + hcenter);
	}
	ctx.stroke();
}
var src = [
"""
		List.duplicate(0, 300)
		|> vin
		|> Enum.map(fn x -> 
            IO.puts(x)
            IO.puts ","
        end)
IO.puts """

];
var dst = [
"""
        List.duplicate(0, 300)
		|> vin
        |> lpf
		|> Enum.map(fn x -> 
            IO.puts(x * 9)
            IO.puts ","
        end)
IO.puts """

];
draw(src, 0);
draw(dst, 1);
</script></body></html>
"""
	end
end
Main.main




実行結果

image.png

成果物

以上。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?