-1

I am currently looking into the polyfit lib for python. I do have a specific input value A and a desired output value B. I want to generate a randomized polynom with a comlexity 5 <= n <= 10, that, when given A as input has B as solution. What would be the best way to achieve that?

Kyu96
  • 1,159
  • 2
  • 17
  • 35
  • So you're asking: given `f(x) = m*x^5 + n*x^4 + o*x^3 + p*x^2 + q*x + r`, choose values for `m` through `r` so that f(A) == B? How about this: pick random values for `m` through `q`, then adjust `r` up or down until f(A) equals B. You could even do it in constant time. – Kevin Jun 21 '18 at 12:45
  • yes thats pretty much what I am trying to do. How am I supposed to do that in constant time? – Kyu96 Jun 21 '18 at 12:52
  • On second thought, it's not constant time, but linear time with respect to degree. But that's almost as good as constant time, since degree won't go above 10 anyway. – Kevin Jun 21 '18 at 13:38

1 Answers1

2

As I suggested in my comment, if you only need to fit a single value, you can pick arbitrary values for all of the coefficients, then adjust the final coefficient so the curve passes through the point you want. This is basically equivalent to drawing a curve on a graph, then sliding it up or down until it intersects a desired point.

import random

def generate_polynomial(degree, a, b):
    """chooses coefficients for a polynomial of the given degree, such that f(a) == b"""

    #to fit only one data point, we can choose arbitrary values for every coefficient except one, which we initially set to zero.
    coefficients = [0] + [random.randint(1, 10) for _ in range(degree-1)]

    #now calculate f(a). This will probably not be equal to b, initially.
    y = sum(coefficient * a**n for n, coefficient in enumerate(coefficients))

    #setting the final coefficient to their difference will cause f(a) to equal b.
    coefficients[0] = b - y

    return coefficients

seq = generate_polynomial(3, 4, 42)
print(seq)

One possible result:

[-18, 7, 2]

This corresponds to f(x) == 2*x^2 + 7*x - 18. It is easy to confirm by hand that f(4) == 2*16 + 7*4 - 18 = 42.

Kevin
  • 74,910
  • 12
  • 133
  • 166
  • Another option is to generate a random polynomial `g`, then multiply every coefficient by `B/g(A)`. One would only have to watch that `A` is not a root of `g`, but one could compose `g` in its factored form, i.e. first generating its `n` roots (careful not to choose `A`) and then taking `prod(x-x_i)` for every root. – Andras Deak -- Слава Україні Jun 21 '18 at 13:15