CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Thread: Polynomials

  1. #1
    Join Date
    Jan 2002
    Posts
    10

    Polynomials

    Ok this is the problem, I have the rest of the program done, but I need a function that evaluates a polynomial. Say it is 5x^3+2x^2+X+3
    Index and power : 3 2 1 0
    The array: coefcients |5||2||1||3|

    I need to be able to plug 4 into this and get an answer back. I am have been tryin it for a long *** time, anybody have a way to do it? Thanks


  2. #2
    Join Date
    Aug 2000
    Posts
    6

    Re: Polynomials

    I can give you some theory here and also a basic inkling... see if it helps... OK?

    the expression anxn + an-1xn-1 + …. A1x1 + a0x0
    can be evaluated as

    x(x(x(… x(an) + an-1) + … ) + a0

    for example,
    5x3 + 2x2 + x + 3
    really is
    x(x(x( 5 ) + 2 ) + 1 ) + 3

    so all u wld need wld be the array of coefficients and the power of the expression

    i.e., given {5, 2, 1, 3} and the value of x to be evaluated at, say 4

    u cld write something like

    int n = sizeof(a ) / sizeof(a[0])
    double d = 0.0;

    for (int k = 0, k < n - 1, k++)
    {
    d += a[k]
    d *= x;
    }
    d += a[n-1];

    or something similar…. U may want to verify the boundary condtions.

    Hope this helps

    -sammy








  3. #3
    Join Date
    Oct 2000
    Location
    London, England
    Posts
    4,773

    Re: Polynomials

    In this example order is the order of the polynomial. The size of the array coeffs is order+1


    double poly( double *coeffs, int order, double x )
    {
    assert ( order > 0 );
    double result = coeffs[ order ];
    while ( order-- )
    {
    result *= x;
    result += coeffs[order];
    }
    return result;
    }





    The best things come to those who rate

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured