โจทย์
เขียนโปรแกรมใช้งานอัลกอริทึมถดถอยเชิงเส้น ผู้ใช้ป้อนจำนวนค่าทั้งหมด
วิธีแก้
ถดถอยเชิงเส้นหาความสัมพันธ์ระหว่างตัวแปรสองตัวโดยใช้สมการเชิงเส้น ตัวแปรหนึ่งเป็นตัวอธิบาย (explanatory) อีกตัวเป็นตัวแปรตาม (dependent)
ตรรกะการคำนวณ:
for(i=0;i<n;i++){ printf("enter values of x and y"); scanf("%f%f",&x,&y); sumx=sumx+x; sumxsq=sumxsq+(x*x); sumy=sumy+y; sumxy=sumxy+(x*y); } d=n*sumxsq-sumx*sumx; m=(n*sumxy-sumx*sumy)/d; c=(sumy*sumxsq-sumx*sumxy)/d;
สุดท้ายพิมพ์ค่า m และ c
ตัวอย่าง
โปรแกรม C คำนวณถดถอยเชิงเส้น:
#include<math.h> #include<stdio.h> main(){ int n,i; float x,y,m,c,d; float sumx=0,sumxsq=0,sumy=0,sumxy=0; printf("enter the number of values for n:"); scanf("%d",&n); for(i=0;i<n;i++){ printf("enter values of x and y"); scanf("%f%f",&x,&y); sumx=sumx+x; sumxsq=sumxsq+(x*x); sumy=sumy+y; sumxy=sumxy+(x*y); } d=n*sumxsq-sumx*sumx; m=(n*sumxy-sumx*sumy)/d; c=(sumy*sumxsq-sumx*sumxy)/d; printf("M=%f\tC=%f\n",m,c); }
ผลลัพธ์
enter the number of values for n:5 enter values of x and y1 5 enter values of x and y2 6 enter values of x and y2 4 enter values of x and y3 7 enter values of x and y1 1 M=2.000000 C=1.000000