假如有一组数:
float x[n]
现在找一个数y,使:
(y-x[0])*(y-x[0])+(y-x[1])*(y-x[1])+(y-x[2])*(y-x[2])+…………+(y-x[n])*(y-x[n])
最小高手帮帮呀

解决方案 »

  1.   

    高中的数学问题。,方差计算什么的一个简单的方法,y=x[min]~x[max],穷举就好啦但是float的精度不能保证
      

  2.   

    是怎么解决的啊,,交流一下啦?
    我觉得是平均值的,,
    如果下面的代码没错,思路也没错的话,就差不多可证明了// TestConsole.cpp : Defines the entry point for the console application.
    //#include "stdafx.h"
    #include <windows.h>
    #include <math.h>
    #include <iostream>
    #include <algorithm>using namespace std;int main(int argc, char* argv[])
    { /*
    int array2[2][3]={{11,12,13},{21,22,23}};    //声明二维int型数组
        for(int i=0;i<2;i++)
        {
            cout<<*(array2+i)<<endl;        //输出二维数组第i行的首地址
            for(int j=0;j<3;j++)
            {
                cout<<*(*(array2+i)+j)<<" ";        //逐个输出二维数组第i行元素值
            }
            cout<<endl;
        }
    */
    double fun(float *x, int n, float y); //最小平方 int N = 10; //数组大小
    float y = 0.;                                   // 所求
    int i = 0; //index
    const float deta = 0.000001f; //误差
    int l = 0; //均值所在位置
    float e = 0.; //均值
    float min,max,t; // cout << "输入数组大小:" << endl;
    cin >> N;
    cout << endl;

    float *x = new float [N]; //生成数组
    cout.precision(10);
    cout << "生成数组...\n";
    srand(GetTickCount());
    for (i=0; i<N; i++)
    {
    x[i] = (float)((rand()%100)*3.14);
    }
    for (i=0; i<N; i++) //输出数组
    {
    cout << i+1 << "\t" <<  x[i] << "\t-->\t" << fun(x,N,x[i]) << endl;
    }
    sort(x, x+N); //数组排序
    cout << endl;
    cout << "显示排序后的数组..." << endl;
    for (i=0; i<N; i++)
    {
    cout << i+1 << "\t" <<  x[i] << "\t-->\t" << fun(x,N,x[i]) << endl;
    }
    for (i=0; i<N; i++) //数组的平均值
    {
    e += x[i];
    }
    e /= N;
    cout << endl;
    cout << "显示数组的平均值:" << endl;
    cout << e << "\t-->\t" << fun(x,N,e) << endl;
    for (i=0; i<N; i++) //查找均值在数组中的位置
    {
    if (x[i] > e)
    {
    l = i;
    if (i>0)
    {
    min = x[i-1];
    }
    else
    {
    min = x[i];
    }
    max = x[i];
    break;
    }
    }

    while (abs(fun(x,N,max)-fun(x,N,min)) > deta) // 最后一步还有问题,,吃饭先
    {
    t = (max + min)/2; if (fun(x,N,t) > fun(x,N,e))
    {
    if (t > e)
    {
    min = e;
    max = t;
    }
    else
    {
    min = t;
    max = e;
    }
    }
    else
    {
    e = t;
    min = e;
    }
    }

    //y = min;
    cout << endl;
    cout << "最小平方值:min" << endl;
    cout << min << "\t-->\t" << fun(x,N,min) << endl; //y = max;
    cout << endl;
    cout << "最小平方值:max" << endl;
    cout << max << "\t-->\t" << fun(x,N,max) << endl;

    return 0;
    }double fun(float *x, int n, float y)
    {
    if (NULL == x)
    {
    return 0.;
    }
    if (n < 1)
    {
    return 0.;
    }

    double r = 0.;
    for (int i=0; i<n; i++)
    {
    r += ((y - x[i])*(y - x[i]));
    }
    return r;
    }