From 57810dc9b1ff8993050bc5e19474d915d47d0d6e Mon Sep 17 00:00:00 2001 From: e78783 Date: Tue, 17 May 2022 20:41:27 +0800 Subject: blogpost, julia soln, edit ch-2.pl --- challenge-165/cheok-yin-fung/blog.txt | 1 + challenge-165/cheok-yin-fung/julia/ch-2.jl | 81 ++++++++++++++++++++++++++++++ challenge-165/cheok-yin-fung/perl/ch-2.pl | 9 ++-- 3 files changed, 86 insertions(+), 5 deletions(-) create mode 100644 challenge-165/cheok-yin-fung/blog.txt create mode 100644 challenge-165/cheok-yin-fung/julia/ch-2.jl diff --git a/challenge-165/cheok-yin-fung/blog.txt b/challenge-165/cheok-yin-fung/blog.txt new file mode 100644 index 0000000000..b5566b2f41 --- /dev/null +++ b/challenge-165/cheok-yin-fung/blog.txt @@ -0,0 +1 @@ +https://e7-87-83.github.io/coding/challenge_165.html diff --git a/challenge-165/cheok-yin-fung/julia/ch-2.jl b/challenge-165/cheok-yin-fung/julia/ch-2.jl new file mode 100644 index 0000000000..bd0113f50d --- /dev/null +++ b/challenge-165/cheok-yin-fung/julia/ch-2.jl @@ -0,0 +1,81 @@ +#!/usr/bin/perl +# The Weekly Challenge 165 +# Task 2 Line of Best Fit +# Julia Solution +# ref: +# https://jahoo.github.io/2021/01/11/simplest_linear_regression_example.html + + +using Plots + +data = [ +333,129 , +39,189 , +140,156 , +292,134 , +393,52 , +160,166 , +362,122 , +13,193 , +341,104 , +320,113 , +109,177 , +203,152 , +343,100 , +225,110 , +23,186 , +282,102 , +284,98 , +205,133 , +297,114 , +292,126 , +339,112 , +327,79 , +253,136 , +61,169 , +128,176 , +346,72 , +316,103 , +124,162 , +65,181 , +159,137 , +212,116 , +337,86 , +215,136 , +153,137 , +390,104 , +100,180 , +76,188 , +77,181 , +69,195 , +92,186 , +275,96 , +250,147 , +34,174 , +213,134 , +186,129 , +189,154 , +361,82 , +363,89 , +] + +xs = [] +ys = [] + +for i = 1:2:length(data)-1 + push!(xs,data[i]) +end + +for i = 2:2:length(data) + push!(ys,data[i]) +end + +scatter(xs, ys) + +A = convert(Matrix{Float64}, hcat(xs, ones(length(xs)))) + +slope, intercept = inv(transpose(A)*A)*transpose(A) * ys + +plot!(x -> slope*x + intercept, legend = :none) + +savefig("new_julia.svg") diff --git a/challenge-165/cheok-yin-fung/perl/ch-2.pl b/challenge-165/cheok-yin-fung/perl/ch-2.pl index 4cc8f19c0a..7d0c7fb658 100644 --- a/challenge-165/cheok-yin-fung/perl/ch-2.pl +++ b/challenge-165/cheok-yin-fung/perl/ch-2.pl @@ -19,18 +19,17 @@ while (<>) { my $n = scalar @points; my $slope = - ( $n * sum(map {$_->[0]*$_->[1]} @points) - - sum(map{$_->[0]} @points) * sum(map{$_->[1]} @points) ) - / ( $n * sum(map{$_->[0]**2} @points) + ( $n * sum(map {$_->[0]*$_->[1]} @points) # n sum(xy) - sum(x) sum(y) + - sum(map{$_->[0]} @points) * sum(map{$_->[1]} @points) ) + / ( $n * sum(map{$_->[0]**2} @points) # n sum(sq x) - sq(sum x) - (sum( map { $_->[0]} @points ))**2) ; my $intercept = - ( sum( map {$_->[1]} @points ) + ( sum( map {$_->[1]} @points ) # sum(y) - slope * sum(x) - $slope * sum( map {$_->[0]} @points) ) / $n ; - sub y_best_fit { my $x = $_[0]; return $slope*$x + $intercept; -- cgit