-
-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathequation_linear.cpp
More file actions
83 lines (78 loc) · 2.44 KB
/
Copy pathequation_linear.cpp
File metadata and controls
83 lines (78 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/**
* @file equation_linear.cpp
* @brief mememasukan persamaan linear
* dengan memiliki intercept dan gradien pada persamaan
* refence
*/
#include<iostream>
#include<vector>
#include<cmath>
#include <exception>
#include <numeric>
/**
* @brief fungsi untuk menghitung mengetahui persamaan
* persamaan linear dengan menentukan gradien dan interpreted
* @param x merupakan input data bebas (independent)
* @param y merupakan input data kaku (dependent)
* @throw invalid_argument panjang data
* @return berupa vector isinya interpreted dan coeffient
*/
template <typename T> std::vector<float> persamaan_garis(const std::vector<T>&x,const std::vector<T>&y){
if (x.size()!=y.size()){
throw std::invalid_argument("Ukurannya tidak pas");
}
int n=x.size();
std::vector<float>result;
std::vector<T>x_2;
std::vector<T>y_2;
std::vector<T>xy;
// pangkat x
for(int i=0;i<x.size();i++){
float pangkat=pow(x[i],2);
x_2.push_back(pangkat);
}
// pangkat yang y
for(int i=0;i<y.size();i++){
float pangkat=pow(y[i],2);
y_2.push_back(pangkat);
}
for(int i=0;i<x.size();i++){
float kali=x[i]*y[i];
xy.push_back(kali);
}
float b0 = (std::accumulate(y.begin(), y.end(), 0.0) * std::accumulate(x_2.begin(), x_2.end(), 0.0))
/ ((n * std::accumulate(x_2.begin(), x_2.end(), 0.0)) - std::pow(std::accumulate(x.begin(), x.end(), 0.0), 2));
float b1 = ((n * std::accumulate(xy.begin(), xy.end(), 0.0)) - (std::accumulate(x.begin(), x.end(), 0.0) * std::accumulate(y.begin(), y.end(), 0.0)))
/ ((n * std::accumulate(x_2.begin(), x_2.end(), 0.0)) - std::pow(std::accumulate(x.begin(), x.end(), 0.0), 2));
result.push_back(b0);
result.push_back(b1);
return result;
}
int main()
{
std::vector<int>x={1,3,4,5,8};
std::vector<int>y={4,2,1,0,0};
std::vector<float>persamaan=persamaan_garis(x,y);
std::cout<<"vector values:";
for(const auto& value:persamaan){
std::cout<<value<<" ";
}
std::cout << std::endl;
// bagaimana kalau panjang data nggak ada;
try
{
/* code */
x={1,3,4,5,8};
y={4,2,1};
std::vector<float> persamaan=persamaan_garis(x,y);
for(const auto& value : persamaan){
std::cout<<value <<" ";
}
std::cout<<std::endl;
}
catch(const std::exception& e)
{
std::cerr << e.what() << '\n';
}
return 0;
}