Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6836979
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T23:25:16+00:00 2026-05-26T23:25:16+00:00

I am trying to write a curve fitting function which returns the optimal parameters

  • 0

I am trying to write a curve fitting function which returns the optimal parameters a, b and c, here is a simplified example:

import numpy
import scipy
from scipy.optimize import curve_fit

def f(x, a, b, c):
    return x * 2*a + 4*b - 5*c

xdata = numpy.array([1,3,6,8,10])
ydata = numpy.array([  0.91589774,   4.91589774,  10.91589774,  14.91589774,  18.91589774])
popt, pcov = scipy.optimize.curve_fit(f, xdata, ydata)

This works fine, but I want to give the user a chance to supply some (or none) of the parameters a, b or c, in which case they should be treated as constants and not estimated. How can I write f so that it fits only the parameters not supplied by the user?

Basically, I need to define f dynamically with the correct arguments. For instance if a was known by the user, f becomes:

def f(x, b, c):
    a = global_version_of_a
    return x * 2*a + 4*b - 5*c
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T23:25:17+00:00Added an answer on May 26, 2026 at 11:25 pm

    Taking a page from the collections.namedtuple playbook, you can use exec to “dynamically” define func:

    import numpy as np
    import scipy.optimize as optimize
    import textwrap
    
    funcstr=textwrap.dedent('''\
    def func(x, {p}):
        return x * 2*a + 4*b - 5*c
    ''')
    def make_model(**kwargs):
        params=set(('a','b','c')).difference(kwargs.keys())
        exec funcstr.format(p=','.join(params)) in kwargs
        return kwargs['func']
    
    func=make_model(a=3, b=1)
    
    xdata = np.array([1,3,6,8,10])
    ydata = np.array([  0.91589774,   4.91589774,  10.91589774,  14.91589774,  18.91589774])
    popt, pcov = optimize.curve_fit(func, xdata, ydata)
    print(popt)
    # [ 5.49682045]
    

    Note the line

    func=make_model(a=3, b=1)
    

    You can pass whatever parameters you like to make_model. The parameters you pass to make_model become fixed constants in func. Whatever parameters remain become free parameters that optimize.curve_fit will try to fit.

    For example, above, a=3 and b=1 become fixed constants in func. Actually, the exec statement places them in func‘s global namespace. func is thus defined as a function of x and the single parameter c. Note the return value for popt is an array of length 1 corresponding to the remaining free parameter c.


    Regarding textwrap.dedent: In the above example, the call to textwrap.dedent is unnecessary. But in a “real-life” script, where funcstr is defined inside a function or at a deeper indentation level, textwrap.dedent allows you to write

    def foo():
        funcstr=textwrap.dedent('''\
            def func(x, {p}):
                return x * 2*a + 4*b - 5*c
            ''')
    

    instead of the visually unappealing

    def foo():
        funcstr='''\
    def func(x, {p}):
        return x * 2*a + 4*b - 5*c
    '''
    

    Some people prefer

    def foo():
        funcstr=(
            'def func(x, {p}):\n'
            '    return x * 2*a + 4*b - 5*c'
            )
    

    but I find quoting each line separately and adding explicit EOL characters a bit onerous. It does save you a function call however.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to write a program wit Perl which should returns the frequency
I'm trying write a query to find records which don't have a matching record
Im trying to write a function for adding category: function addCategory() { $cname =
I'm trying to write a regex function that will identify and replace a single
I'm trying to write a blog post which includes a code segment inside a
Trying to write a matrix-multiplying function for arbitrary-sized matrices in C. I'm trying the
I'm trying to write a simple program which uses libcurl to perform HTTP POST
I've been trying write an application which will be able to connect to a
I am trying to write elliptic curve point addition using where clause. I am
I am trying to write a data calculated from this function in a file.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.