# Curve Fitting y = ax^b Python Program

This Python program implements least square method to fit curve of type y = axb.

We first read n data points from user and then we implement curve fitting for y = axb using least square approach in Python programming language as follow:

## Python Source Code: Fitting y = axb

``````
# This is naive approach, there are shortcut methods for doing it!
# Least square method
# Fitting y = ax^b to given n data points
import numpy as np

n = int(input("How many data points? "))

# Creating numpy array x & y to store n data points
x = np.zeros(n)
y = np.zeros(n)

print("Enter data:")
for i in range(n):
x[i] = float(input("x["+str(i)+"]= "))
y[i] = float(input("y["+str(i)+"]= "))

# Finding required sum for least square methods
sumX,sumX2,sumY,sumXY = 0,0,0,0
for i in range(n):
sumX = sumX + np.log(x[i])
sumX2 = sumX2 +np.log(x[i])*np.log(x[i])
sumY = sumY + np.log(y[i])
sumXY = sumXY + np.log(x[i])*np.log(y[i])

# Finding coefficients A and B
b = (n*sumXY-sumX*sumY)/(n*sumX2-sumX*sumX)
A = (sumY - b*sumX)/n

# Obtaining a and b
a = np.exp(A)

# Displaying coefficients a, b & equation
print("\nCoefficients are:")
print("a: ", a)
print("b: ", b)
``````

## Output

```How many data points? 4
Enter data:
x= 61
y= 350
x= 26
y= 400
x= 7
y= 500
x= 2.6
y= 600

Coefficients are:
a:  701.9919475945616
b:  -0.1708554336187208
```