# Wolfram Function Repository

Instant-use add-on functions for the Wolfram Language

Function Repository Resource:

Fit a power law to data

Contributed by:
Sander Huisman

ResourceFunction["FitPowerLaw"][ fits | |

ResourceFunction["FitPowerLaw"][ fits |

ResourceFunction["FitPowerLaw"] effectively fits the function a x^{b} to the data, but does so by fitting the linear function c x+d to the log of the data.

ResourceFunction["FitPowerLaw"] fits in 'log space' such that fits that span multiple decades of data are not dominated by a few of the largest values and the smallest values are basically neglegible. The errors are therefore not in the sense of a classical least-square but rather the square of the log of the ratio of the fitted value and the original data. Visually this then results in a 'good fit' when the data is visualized in a log-log plot of the data.

The data *data* should either be a list of points {*y*_{1}, *y*_{2}, *y*_{3}, …,*y*_{n}} (to which the *x* coordinates 1 through *n* are assigned), or the data is {*x*,*y*} pairs: {{*x*_{1},*y*_{1}},{*x*_{2},*y*_{2}},…}, for a list of lists of *data* ResourceFunction["FitPowerLaw"] will fit each sublist, returning in that case a list of associations.

Only positive values are fitted. Negative points are ignored.

ResourceFunction["FitPowerLaw"] has the following options:

If both options are given, only the "Prefactor" option is used.

ResourceFunction["FitPowerLaw"] returns an Association with fit and fit parameters.

Create some data and fit it:

In[1]:= |

Out[1]= |

For a single list of values the x coordinates are assumed to be 1,2,3,4…:

In[2]:= |

Out[2]= |

In[3]:= |

Out[3]= |

For a list of lists of data each list will be fitted separately:

In[4]:= |

Out[4]= |

For a list of pairs the data is assumed to be in {x,y} pairs:

In[5]:= |

Out[5]= |

Prescribe the exponent:

In[6]:= |

Out[8]= |

Prescribe the prefactor:

In[9]:= |

Out[10]= |

Create some data, fit it, and then plot both:

In[11]:= |

Out[12]= |

The difference between a classical least-squares fit or the fitting of the least-squares in log-space becomes very apparent when fitting over several decades. Because the error is much larger for the higher decades the error is completely dominated by those larger points, resulting in a strange fit when viewed in log-space:

In[13]:= |

Out[16]= |

The error for the classical method is lower:

In[17]:= |

Out[19]= |

But not in log space, here the current method is lower:

In[20]:= |

Out[22]= |

- 1.0.0 – 07 October 2022

This work is licensed under a Creative Commons Attribution 4.0 International License