OOP31-apro
.htmlЛинейная аппроксимация с прогнозом body { font-family: Arial, sans-serif; margin: 20px; } .container { display: flex; flex-direction: column; max-width: 800px; } #results { margin-top: 20px; } #chartContainer { width: 100%; height: 400px; margin-top: 20px; } .prediction { margin-top: 15px; padding: 10px; background-color: #f0f0f0; border-radius: 5px; } .prediction input { width: 80px; } .prediction button { margin-left: 10px; } Линейная аппроксимация методом наименьших квадратов Введите данные (12 точек x и y): Вычислить аппроксимацию Сгенерировать случайные данные Результаты:
Прогнозирование значения y: Введите x: Вычислить y
// Инициализация данных const dataPoints = 12; let xValues = []; let yValues = []; let currentA = 0; let currentB = 0; // Создаем поля для ввода const inputFields = document.getElementById('inputFields'); for (let i = 0; i < dataPoints; i++) { const div = document.createElement('div'); div.innerHTML = ` Точка ${i+1}: x = y = `; inputFields.appendChild(div); } // Функция для чтения данных из полей ввода function readInputData() { xValues = []; yValues = []; for (let i = 0; i < dataPoints; i++) { const xInput = document.getElementById(`x${i}`); const yInput = document.getElementById(`y${i}`); if (xInput.value && yInput.value) { xValues.push(parseFloat(xInput.value)); yValues.push(parseFloat(yInput.value)); } } return { x: xValues, y: yValues }; } // Функция линейной аппроксимации (метод наименьших квадратов) function linearApproximation(x, y) { const n = x.length; let sumX = 0, sumY = 0, sumXY = 0, sumXX = 0; for (let i = 0; i < n; i++) { sumX += x[i]; sumY += y[i]; sumXY += x[i] * y[i]; sumXX += x[i] * x[i]; } // Вычисляем коэффициенты a и b для уравнения y = a*x + b const a = (n * sumXY - sumX * sumY) / (n * sumXX - sumX * sumX); const b = (sumY - a * sumX) / n; // Вычисляем среднеквадратичную ошибку let error = 0; for (let i = 0; i < n; i++) { error += Math.pow(y[i] - (a * x[i] + b), 2); } error = Math.sqrt(error / n); return { a, b, error }; } // Функция для отображения результатов function displayResults(a, b, error) { currentA = a; currentB = b; const equationText = `Уравнение аппроксимирующей прямой: y = ${a.toFixed(4)}x + ${b.toFixed(4)}`; const errorText = `Среднеквадратичная ошибка: ${error.toFixed(4)}`; document.getElementById('equation').textContent = equationText; document.getElementById('error').textContent = errorText; } // Функция для вычисления y по x function calculateY(x) { return currentA * x + currentB; } // Функция для построения графика function plotData(x, y, a, b) { const ctx = document.getElementById('dataChart').getContext('2d'); // Если уже есть график - уничтожаем его if (window.dataChart) { window.dataChart.destroy(); } // Создаем точки для аппроксимирующей прямой const lineX = [Math.min(...x), Math.max(...x)]; const lineY = lineX.map(x => a * x + b); window.dataChart = new Chart(ctx, { type: 'scatter', data: { datasets: [ { label: 'Исходные данные', data: x.map((val, i) => ({x: val, y: y[i]})), backgroundColor: 'rgba(75, 192, 192, 1)', pointRadius: 6 }, { label: 'Аппроксимирующая прямая', data: lineX.map((val, i) => ({x: val, y: lineY[i]})), type: 'line', borderColor: 'rgba(255, 99, 132, 1)', borderWidth: 2, pointRadius: 0, fill: false } ] }, options: { responsive: true, scales: { x: { type: 'linear', position: 'bottom' } } } }); } // Обработчик кнопки вычисления document.getElementById('calculateBtn').addEventListener('click', function() { const data = readInputData(); if (data.x.length === dataPoints && data.y.length === dataPoints) { const { a, b, error } = linearApproximation(data.x, data.y); displayResults(a, b, error); plotData(data.x, data.y, a, b); } else { alert('Пожалуйста, введите все 12 значений x и y'); } }); // Обработчик кнопки случайных данных document.getElementById('randomDataBtn').addEventListener('click', function() { // Генерируем случайные данные с линейной зависимостью + шум const randomA = (Math.random() * 4 - 2); // от -2 до 2 const randomB = (Math.random() * 20 - 10); // от -10 до 10 for (let i = 0; i < dataPoints; i++) { const x = i; const y = randomA * x + randomB + (Math.random() * 4 - 2); // линейная зависимость + шум document.getElementById(`x${i}`).value = x; document.getElementById(`y${i}`).value = y.toFixed(2); } }); // Обработчик кнопки прогнозирования document.getElementById('predictBtn').addEventListener('click', function() { if (currentA === 0 && currentB === 0) { alert('Сначала выполните аппроксимацию данных'); return; } const x = parseFloat(document.getElementById('predictX').value); if (isNaN(x)) { alert('Введите корректное значение x'); return; } const y = calculateY(x); document.getElementById('predictionResult').textContent = `Для x = ${x}, прогнозируемое y = ${y.toFixed(4)}`; });
