精华内容
下载资源
问答
  • MATLAB优化函数fmincon解析

    万次阅读 多人点赞 2019-08-16 11:27:10
    MATLAB,优化函数fmincon解析 [x,fval,exitflag,output,lambda,grad,hessian]=fmincon(fun,x0,A,b,Aeq,beq,lb,ub,nonlcon,options); ...

    MATLAB,优化函数fmincon解析

    [x,fval,exitflag,output,lambda,grad,hessian]=fmincon(fun,x0,A,b,Aeq,beq,lb,ub,nonlcon,options);                                                                                      

    输入参数:fun要求解的函数值;x0函数fun参数值的初始化;

                       参数值的线性不等式约束A,b

                      参数值的等式线性约束Aeq,beq,

                       参数值的上界和下界lb,ub

                       非线性约束nonlcon

                     

    输出参数:X输出最优参数值

                       Fval输出fun在X参数的值

                       Exitflag输出fmincon额外条件值

    function [X,FVAL,EXITFLAG,OUTPUT,LAMBDA,GRAD,HESSIAN] = fmincon(FUN,X,A,B,Aeq,Beq,LB,UB,NONLCON,options,varargin)
    /*fmincon可以在多元函数中找到最小值
       FMINCON attempts to solve problems of the form:
      min F(X)  subject to:  A*X  <= B, Aeq*X  = Beq (linear constraints)线性约束
        X                     C(X) <= 0, Ceq(X) = 0   (nonlinear constraints)非线性约束
                                  LB <= X <= UB        (bounds)
       */
     /*FMINCON implements four different algorithms: interior point, SQP,
    %   active set, and trust region reflective. Choose one via the option
    %   Algorithm: for instance, to choose SQP, set OPTIONS =
    %   optimoptions('fmincon','Algorithm','sqp'), and then pass OPTIONS to
    %   FMINCON.
    	fmincon函数应用四种不同的算法:内点法(interior point);序列二次规划算法(SQP);有效集法(active set);信赖域有效算法(trust region reflective)。
    	如果采用SQP算法可以设置 OPTIONS = optimoptions('fmincon','Algorithm','sqp'),再把OPTIONS赋给fmincon
         */  
    	/* 
    %   X = FMINCON(FUN,X0,A,B) starts at X0 and finds a minimum X to the 
    %   function FUN, subject to the linear inequalities A*X <= B. FUN accepts 
    %   input X and returns a scalar function value F evaluated at X. X0 may be
    %   a scalar, vector, or matrix. 
    %
    %   X = FMINCON(FUN,X0,A,B,Aeq,Beq) minimizes FUN subject to the linear 
    %   equalities Aeq*X = Beq as well as A*X <= B. (Set A=[] and B=[] if no 
    %   inequalities exist.)
    %
    %   X = FMINCON(FUN,X0,A,B,Aeq,Beq,LB,UB) defines a set of lower and upper
    %   bounds on the design variables, X, so that a solution is found in 
    %   the range LB <= X <= UB. Use empty matrices for LB and UB
    %   if no bounds exist. Set LB(i) = -Inf if X(i) is unbounded below; 
    %   set UB(i) = Inf if X(i) is unbounded above.
    %
    %   X = FMINCON(FUN,X0,A,B,Aeq,Beq,LB,UB,NONLCON) subjects the minimization
    %   to the constraints defined in NONLCON. The function NONLCON accepts X 
    %   and returns the vectors C and Ceq, representing the nonlinear 
    %   inequalities and equalities respectively. FMINCON minimizes FUN such 
    %   that C(X) <= 0 and Ceq(X) = 0. (Set LB = [] and/or UB = [] if no bounds
    %   exist.)
    %
    %   X = FMINCON(FUN,X0,A,B,Aeq,Beq,LB,UB,NONLCON,OPTIONS) minimizes with
    %   the default optimization parameters replaced by values in OPTIONS, an
    %   argument created with the OPTIMOPTIONS function. See OPTIMOPTIONS for
    %   details. For a list of options accepted by FMINCON refer to the
    %   documentation.
    %  
    %   X = FMINCON(PROBLEM) finds the minimum for PROBLEM. PROBLEM is a
    %   structure with the function FUN in PROBLEM.objective, the start point
    %   in PROBLEM.x0, the linear inequality constraints in PROBLEM.Aineq
    %   and PROBLEM.bineq, the linear equality constraints in PROBLEM.Aeq and
    %   PROBLEM.beq, the lower bounds in PROBLEM.lb, the upper bounds in 
    %   PROBLEM.ub, the nonlinear constraint function in PROBLEM.nonlcon, the
    %   options structure in PROBLEM.options, and solver name 'fmincon' in
    %   PROBLEM.solver. Use this syntax to solve at the command line a problem 
    %   exported from OPTIMTOOL. The structure PROBLEM must have all the fields.
    %
    %   [X,FVAL] = FMINCON(FUN,X0,...) returns the value of the objective 
    %   function FUN at the solution X.
    %
    %   [X,FVAL,EXITFLAG] = FMINCON(FUN,X0,...) returns an EXITFLAG that 
    %   describes the exit condition of FMINCON. Possible values of EXITFLAG 
    %   and the corresponding exit conditions are listed below. See the
    %   documentation for a complete description.
    %   */
    
    /*
    %   All algorithms:
    %     1  First order optimality conditions satisfied.
    %     0  Too many function evaluations or iterations.
    %    -1  Stopped by output/plot function.
    %    -2  No feasible point found.
    %   Trust-region-reflective, interior-point, and sqp:
    %     2  Change in X too small.
    %   Trust-region-reflective:
    %     3  Change in objective function too small.
    %   Active-set only:
    %     4  Computed search direction too small.
    %     5  Predicted change in objective function too small.
    %   Interior-point and sqp:
    %    -3  Problem seems unbounded.
    		所有算法中EXITFLAG返回值涵义
    			1  满足一阶最优性条件
    			0	函数计算或迭代太多。无法求解
    			-1 被输出和绘图功能阻止
    			-2	找不到可行点
    			Trust-region-reflective, interior-point, and sqp:三种算法才有的返回值
    			2  X变化太小
    			Active-set 算法才有的返回值
    			4	计算搜索的方向太小
    			5	目标函数的预测变化太小。
    			Interior-point and sqp才有的
    			-3  问题没有边界
    		*/
    /*
    %   [X,FVAL,EXITFLAG,OUTPUT] = FMINCON(FUN,X0,...) returns a structure 
    %   OUTPUT with information such as total number of iterations, and final 
    %   objective function value. See the documentation for a complete list.
      返回包含迭代总数和最终目标函数值等信息的结构输出
    */
    /*
    %   [X,FVAL,EXITFLAG,OUTPUT,LAMBDA] = FMINCON(FUN,X0,...) returns the 
    %   Lagrange multipliers at the solution X: LAMBDA.lower for LB, 
    %   LAMBDA.upper for UB, LAMBDA.ineqlin is for the linear inequalities, 
    %   LAMBDA.eqlin is for the linear equalities, LAMBDA.ineqnonlin is for the
    %   nonlinear inequalities, and LAMBDA.eqnonlin is for the nonlinear 
    %   equalities.
         返回解x处的拉格朗日乘数:lambda.lower表示lb,lambda.upper表示ub,
    	 lambda.ineqlin表示线性不等式,lambda.eqlin表示线性等式,
    	 lambda.ineqnonlin表示非线性不等式,lambda.eqnonlin表示非线性不等式。
    */
    
    /*
    %   [X,FVAL,EXITFLAG,OUTPUT,LAMBDA,GRAD] = FMINCON(FUN,X0,...) returns the 
    %   value of the gradient of FUN at the solution X.
    返回解决方案x的fun渐变值。
    %*/
    /*  [X,FVAL,EXITFLAG,OUTPUT,LAMBDA,GRAD,HESSIAN] = FMINCON(FUN,X0,...) 
    %   returns the value of the exact or approximate Hessian of the Lagrangian
    %   at X. 
    返回X的朗格朗日精确解或者近似Hessian矩阵
    */
    /* Examples
    %     FUN can be specified using @:
    %        X = fmincon(@humps,...)
    %     In this case, F = humps(X) returns the scalar function value F of 
    %     the HUMPS function evaluated at X.
    %
    %     FUN can also be an anonymous function:
    %        X = fmincon(@(x) 3*sin(x(1))+exp(x(2)),[1;1],[],[],[],[],[0 0])
    %     returns X = [0;0].
    %
    %   If FUN or NONLCON are parameterized, you can use anonymous functions to
    %   capture the problem-dependent parameters. Suppose you want to minimize 
    %   the objective given in the function myfun, subject to the nonlinear 
    %   constraint mycon, where these two functions are parameterized by their 
    %   second argument a1 and a2, respectively. Here myfun and mycon are 
    %   MATLAB file functions such as
    %
    %        function f = myfun(x,a1)      
    %        f = x(1)^2 + a1*x(2)^2;       
    %                                      
    %        function [c,ceq] = mycon(x,a2)
    %        c = a2/x(1) - x(2);
    %        ceq = [];
    %
    %   To optimize for specific values of a1 and a2, first assign the values 
    %   to these two parameters. Then create two one-argument anonymous 
    %   functions that capture the values of a1 and a2, and call myfun and 
    %   mycon with two arguments. Finally, pass these anonymous functions to 
    %   FMINCON:
    %
    %        a1 = 2; a2 = 1.5; % define parameters first
    %        options = optimoptions('fmincon','Algorithm','interior-point'); % run interior-point algorithm
    %        x = fmincon(@(x) myfun(x,a1),[1;2],[],[],[],[],[],[],@(x) mycon(x,a2),options)
    %
    %   See also OPTIMOPTIONS, OPTIMTOOL, FMINUNC, FMINBND, FMINSEARCH, @, FUNCTION_HANDLE.
    
    %   Copyright 1990-2013 The MathWorks, Inc.
    */
    defaultopt = struct( ...
        'Algorithm','interior-point', ...
        'AlwaysHonorConstraints','bounds', ...
        'DerivativeCheck','off', ...
        'Diagnostics','off', ...
        'DiffMaxChange',Inf, ...
        'DiffMinChange',0, ...
        'Display','final', ...
        'FinDiffRelStep', [], ...
        'FinDiffType','forward', ...    
        'FunValCheck','off', ...
        'GradConstr','off', ...
        'GradObj','off', ...
        'HessFcn',[], ...
        'Hessian',[], ...    
        'HessMult',[], ...
        'HessPattern','sparse(ones(numberOfVariables))', ...
        'InitBarrierParam',0.1, ...
        'InitTrustRegionRadius','sqrt(numberOfVariables)', ...
        'MaxFunEvals',[], ...
        'MaxIter',[], ...
        'MaxPCGIter','max(1,floor(numberOfVariables/2))', ...
        'MaxProjCGIter','2*(numberOfVariables-numberOfEqualities)', ...    
        'MaxSQPIter','10*max(numberOfVariables,numberOfInequalities+numberOfBounds)', ...
        'ObjectiveLimit',-1e20, ...
        'OutputFcn',[], ...
        'PlotFcns',[], ...
        'PrecondBandWidth',0, ...
        'RelLineSrchBnd',[], ...
        'RelLineSrchBndDuration',1, ...
        'ScaleProblem','none', ...
        'SubproblemAlgorithm','ldl-factorization', ...
        'TolCon',1e-6, ...
        'TolConSQP',1e-6, ...    
        'TolFun',1e-6, ...
        'TolPCG',0.1, ...
        'TolProjCG',1e-2, ...
        'TolProjCGAbs',1e-10, ...
        'TolX',[], ...
        'TypicalX','ones(numberOfVariables,1)', ...
        'UseParallel',false ...
        );
    
    % If just 'defaults' passed in, return the default options in X
    if nargin==1 && nargout <= 1 && strcmpi(FUN,'defaults')
       X = defaultopt;
       return
    end
    
    if nargin < 10
        options = [];
        if nargin < 9
            NONLCON = [];
            if nargin < 8
                UB = [];
                if nargin < 7
                    LB = [];
                    if nargin < 6
                        Beq = [];
                        if nargin < 5
                            Aeq = [];
                        end
                    end
                end
            end
        end
    end
    
    problemInput = false;
    if nargin == 1
        if isa(FUN,'struct')
            problemInput = true;
            [FUN,X,A,B,Aeq,Beq,LB,UB,NONLCON,options] = separateOptimStruct(FUN);
        else % Single input and non-structure.
            error(message('optimlib:fmincon:InputArg'));
        end
    end
    
    % Prepare the options for the solver
    [options, optionFeedback] = prepareOptionsForSolver(options, 'fmincon');
    
    if nargin < 4 && ~problemInput
      error(message('optimlib:fmincon:AtLeastFourInputs'))
    end
    
    if isempty(NONLCON) && isempty(A) && isempty(Aeq) && isempty(UB) && isempty(LB)
       error(message('optimlib:fmincon:ConstrainedProblemsOnly'))
    end
    
    % Check for non-double inputs
    msg = isoptimargdbl('FMINCON', {'X0','A','B','Aeq','Beq','LB','UB'}, ...
                                     X,  A,  B,  Aeq,  Beq,  LB,  UB);
    if ~isempty(msg)
        error('optimlib:fmincon:NonDoubleInput',msg);
    end
    
    if nargout > 4
       computeLambda = true;
    else 
       computeLambda = false;
    end
    
    activeSet = 'medium-scale: SQP, Quasi-Newton, line-search';
    sqp = 'sequential quadratic programming';
    trustRegionReflective = 'trust-region-reflective';
    interiorPoint = 'interior-point';
    
    [sizes.xRows,sizes.xCols] = size(X);
    XOUT = X(:);
    sizes.nVar = length(XOUT);
    % Check for empty X
    if sizes.nVar == 0
       error(message('optimlib:fmincon:EmptyX'));
    end
    
    display = optimget(options,'Display',defaultopt,'fast');
    flags.detailedExitMsg = ~isempty(strfind(display,'detailed'));
    switch display
        case {'off','none'}
            verbosity = 0;
        case {'notify','notify-detailed'}
            verbosity = 1;
        case {'final','final-detailed'}
            verbosity = 2;
        case {'iter','iter-detailed'}
            verbosity = 3;
        case 'testing'
            verbosity = 4;
        otherwise
            verbosity = 2;
    end
    
    % Set linear constraint right hand sides to column vectors
    % (in particular, if empty, they will be made the correct
    % size, 0-by-1)
    B = B(:);
    Beq = Beq(:);
    
    % Check for consistency of linear constraints, before evaluating
    % (potentially expensive) user functions 
    
    % Set empty linear constraint matrices to the correct size, 0-by-n
    if isempty(Aeq)
        Aeq = reshape(Aeq,0,sizes.nVar);
    end
    if isempty(A)
        A = reshape(A,0,sizes.nVar);   
    end
    
    [lin_eq,Aeqcol] = size(Aeq);
    [lin_ineq,Acol] = size(A);
    % These sizes checks assume that empty matrices have already been made the correct size
    if Aeqcol ~= sizes.nVar
       error(message('optimlib:fmincon:WrongNumberOfColumnsInAeq', sizes.nVar))
    end
    if lin_eq ~= length(Beq)
        error(message('optimlib:fmincon:AeqAndBeqInconsistent'))
    end
    if Acol ~= sizes.nVar
       error(message('optimlib:fmincon:WrongNumberOfColumnsInA', sizes.nVar))
    end
    if lin_ineq ~= length(B)
        error(message('optimlib:fmincon:AeqAndBinInconsistent'))
    end
    % End of linear constraint consistency check
    
    Algorithm = optimget(options,'Algorithm',defaultopt,'fast'); 
    
    % Option needed for processing initial guess
    AlwaysHonorConstraints = optimget(options,'AlwaysHonorConstraints',defaultopt,'fast'); 
    
    % Determine algorithm user chose via options. (We need this now
    % to set OUTPUT.algorithm in case of early termination due to 
    % inconsistent bounds.) 
    if strcmpi(Algorithm,'active-set')
        OUTPUT.algorithm = activeSet;
    elseif strcmpi(Algorithm,'sqp')
        OUTPUT.algorithm = sqp;
    elseif strcmpi(Algorithm,'interior-point')
        OUTPUT.algorithm = interiorPoint;
    elseif strcmpi(Algorithm,'trust-region-reflective')
        OUTPUT.algorithm = trustRegionReflective;
    else
        error(message('optimlib:fmincon:InvalidAlgorithm'));
    end    
    
    [XOUT,l,u,msg] = checkbounds(XOUT,LB,UB,sizes.nVar);
    if ~isempty(msg)
       EXITFLAG = -2;
       [FVAL,LAMBDA,GRAD,HESSIAN] = deal([]);
       
       OUTPUT.iterations = 0;
       OUTPUT.funcCount = 0;
       OUTPUT.stepsize = [];
       if strcmpi(OUTPUT.algorithm,activeSet) || strcmpi(OUTPUT.algorithm,sqp)
           OUTPUT.lssteplength = [];
       else % trust-region-reflective, interior-point
           OUTPUT.cgiterations = [];
       end
       if strcmpi(OUTPUT.algorithm,interiorPoint) || strcmpi(OUTPUT.algorithm,activeSet) || ...
          strcmpi(OUTPUT.algorithm,sqp)
           OUTPUT.constrviolation = [];
       end
       OUTPUT.firstorderopt = [];
       OUTPUT.message = msg;
       
       X(:) = XOUT;
       if verbosity > 0
          disp(msg)
       end
       return
    end
    
    % Get logical list of finite lower and upper bounds
    finDiffFlags.hasLBs = isfinite(l);
    finDiffFlags.hasUBs = isfinite(u);
    
    lFinite = l(finDiffFlags.hasLBs);
    uFinite = u(finDiffFlags.hasUBs);
    
    % Create structure of flags and initial values, initialize merit function
    % type and the original shape of X.
    flags.meritFunction = 0;
    initVals.xOrigShape = X;
    
    diagnostics = strcmpi(optimget(options,'Diagnostics',defaultopt,'fast'),'on');
    funValCheck = strcmpi(optimget(options,'FunValCheck',defaultopt,'fast'),'on');
    derivativeCheck = strcmpi(optimget(options,'DerivativeCheck',defaultopt,'fast'),'on');
    
    % Gather options needed for finitedifferences
    % Write checked DiffMaxChange, DiffMinChage, FinDiffType, FinDiffRelStep,
    % GradObj and GradConstr options back into struct for later use
    options.DiffMinChange = optimget(options,'DiffMinChange',defaultopt,'fast');
    options.DiffMaxChange = optimget(options,'DiffMaxChange',defaultopt,'fast');
    if options.DiffMinChange >= options.DiffMaxChange
        error(message('optimlib:fmincon:DiffChangesInconsistent', sprintf( '%0.5g', options.DiffMinChange ), sprintf( '%0.5g', options.DiffMaxChange )))
    end
    % Read in and error check option TypicalX
    [typicalx,ME] = getNumericOrStringFieldValue('TypicalX','ones(numberOfVariables,1)', ...
        ones(sizes.nVar,1),'a numeric value',options,defaultopt);
    if ~isempty(ME)
        throw(ME)
    end
    checkoptionsize('TypicalX', size(typicalx), sizes.nVar);
    options.TypicalX = typicalx;
    options.FinDiffType = optimget(options,'FinDiffType',defaultopt,'fast');
    options = validateFinDiffRelStep(sizes.nVar,options,defaultopt);
    options.GradObj = optimget(options,'GradObj',defaultopt,'fast');
    options.GradConstr = optimget(options,'GradConstr',defaultopt,'fast');
    
    flags.grad = strcmpi(options.GradObj,'on');
    
    % Notice that defaultopt.Hessian = [], so the variable "hessian" can be empty
    hessian = optimget(options,'Hessian',defaultopt,'fast'); 
    % If calling trust-region-reflective with an unavailable Hessian option value, 
    % issue informative error message
    if strcmpi(OUTPUT.algorithm,trustRegionReflective) && ...
            ~( isempty(hessian) || strcmpi(hessian,'on') || strcmpi(hessian,'user-supplied') || ...
               strcmpi(hessian,'off') || strcmpi(hessian,'fin-diff-grads')  )
        error(message('optimlib:fmincon:BadTRReflectHessianValue'))
    end
    
    if ~iscell(hessian) && ( strcmpi(hessian,'user-supplied') || strcmpi(hessian,'on') )
        flags.hess = true;
    else
        flags.hess = false;
    end
    
    if isempty(NONLCON)
       flags.constr = false;
    else
       flags.constr = true;
    end
    
    % Process objective function
    if ~isempty(FUN)  % will detect empty string, empty matrix, empty cell array
       % constrflag in optimfcnchk set to false because we're checking the objective, not constraint
       funfcn = optimfcnchk(FUN,'fmincon',length(varargin),funValCheck,flags.grad,flags.hess,false,Algorithm);
    else
       error(message('optimlib:fmincon:InvalidFUN'));
    end
    
    % Process constraint function
    if flags.constr % NONLCON is non-empty
       flags.gradconst = strcmpi(options.GradConstr,'on');
       % hessflag in optimfcnchk set to false because hessian is never returned by nonlinear constraint 
       % function
       %
       % constrflag in optimfcnchk set to true because we're checking the constraints
       confcn = optimfcnchk(NONLCON,'fmincon',length(varargin),funValCheck,flags.gradconst,false,true);
    else
       flags.gradconst = false; 
       confcn = {'','','','',''};
    end
    
    [rowAeq,colAeq] = size(Aeq);
    
    if strcmpi(OUTPUT.algorithm,activeSet) || strcmpi(OUTPUT.algorithm,sqp)
        % See if linear constraints are sparse and if user passed in Hessian
        if issparse(Aeq) || issparse(A)
            warning(message('optimlib:fmincon:ConvertingToFull', Algorithm))
        end
        if flags.hess % conflicting options
            flags.hess = false;
            warning(message('optimlib:fmincon:HessianIgnoredForAlg', Algorithm));
            if strcmpi(funfcn{1},'fungradhess')
                funfcn{1}='fungrad';
            elseif  strcmpi(funfcn{1},'fun_then_grad_then_hess')
                funfcn{1}='fun_then_grad';
            end
        end
    elseif strcmpi(OUTPUT.algorithm,trustRegionReflective)
        % Look at constraint type and supplied derivatives, and determine if
        % trust-region-reflective can solve problem
        isBoundedNLP = isempty(NONLCON) && isempty(A) && isempty(Aeq); % problem has only bounds and no other constraints 
        isLinEqNLP = isempty(NONLCON) && isempty(A) && isempty(lFinite) ...
            && isempty(uFinite) && colAeq > rowAeq;
        if isBoundedNLP && flags.grad
            % if only l and u then call sfminbx
        elseif isLinEqNLP && flags.grad
            % if only Aeq beq and Aeq has more columns than rows, then call sfminle
        else
            if ~isBoundedNLP && ~isLinEqNLP
                error(message('optimlib:fmincon:ConstrTRR', ...
                    addLink( 'Choosing the Algorithm', 'choose_algorithm' )))            
            else
                % The user has a problem that satisfies the TRR constraint
                % restrictions but they haven't supplied gradients.
                error(message('optimlib:fmincon:GradOffTRR', ...
                    addLink( 'Choosing the Algorithm', 'choose_algorithm' )))
            end
        end
    end
    
    lenvlb = length(l);
    lenvub = length(u);
    
    % Process initial point 
    shiftedX0 = false; % boolean that indicates if initial point was shifted
    if strcmpi(OUTPUT.algorithm,activeSet)
       %
       % Ensure starting point lies within bounds
       %
       i=1:lenvlb;
       lindex = XOUT(i)<l(i);
       if any(lindex)
          XOUT(lindex)=l(lindex); 
          shiftedX0 = true;
       end
       i=1:lenvub;
       uindex = XOUT(i)>u(i);
       if any(uindex)
          XOUT(uindex)=u(uindex);
          shiftedX0 = true;
       end
       X(:) = XOUT;
    elseif strcmpi(OUTPUT.algorithm,trustRegionReflective)
       %
       % If components of initial x not within bounds, set those components  
       % of initial point to a "box-centered" point
       %
       if isempty(Aeq)
           arg = (u >= 1e10); arg2 = (l <= -1e10);
           u(arg) = inf;
           l(arg2) = -inf;
           xinitOutOfBounds_idx = XOUT < l | XOUT > u;
           if any(xinitOutOfBounds_idx)
               shiftedX0 = true;
               XOUT = startx(u,l,XOUT,xinitOutOfBounds_idx);
               X(:) = XOUT;
           end
       else
          % Phase-1 for sfminle nearest feas. pt. to XOUT. Don't print a
          % message for this change in X0 for sfminle. 
           XOUT = feasibl(Aeq,Beq,XOUT);
           X(:) = XOUT;
       end
    
    elseif strcmpi(OUTPUT.algorithm,interiorPoint)
        % Variables: fixed, finite lower bounds, finite upper bounds
        xIndices = classifyBoundsOnVars(l,u,sizes.nVar,true);
    
        % If honor bounds mode, then check that initial point strictly satisfies the
        % simple inequality bounds on the variables and exactly satisfies fixed variable
        % bounds.
        if strcmpi(AlwaysHonorConstraints,'bounds') || strcmpi(AlwaysHonorConstraints,'bounds-ineqs')
            violatedFixedBnds_idx = XOUT(xIndices.fixed) ~= l(xIndices.fixed);
            violatedLowerBnds_idx = XOUT(xIndices.finiteLb) <= l(xIndices.finiteLb);
            violatedUpperBnds_idx = XOUT(xIndices.finiteUb) >= u(xIndices.finiteUb);
            if any(violatedLowerBnds_idx) || any(violatedUpperBnds_idx) || any(violatedFixedBnds_idx)
                XOUT = shiftInitPtToInterior(sizes.nVar,XOUT,l,u,Inf);
                X(:) = XOUT;
                shiftedX0 = true;
            end
        end
    else % SQP
        % Classify variables: finite lower bounds, finite upper bounds
        xIndices = classifyBoundsOnVars(l,u,sizes.nVar,false);
        
        % SQP always honors the bounds. Check that initial point
        % strictly satisfies the bounds on the variables.
        violatedLowerBnds_idx = XOUT(xIndices.finiteLb) < l(xIndices.finiteLb);
        violatedUpperBnds_idx = XOUT(xIndices.finiteUb) > u(xIndices.finiteUb);
        if any(violatedLowerBnds_idx) || any(violatedUpperBnds_idx)
            finiteLbIdx = find(xIndices.finiteLb);
            finiteUbIdx = find(xIndices.finiteUb);
            XOUT(finiteLbIdx(violatedLowerBnds_idx)) = l(finiteLbIdx(violatedLowerBnds_idx));
            XOUT(finiteUbIdx(violatedUpperBnds_idx)) = u(finiteUbIdx(violatedUpperBnds_idx));
            X(:) = XOUT;
            shiftedX0 = true;
        end
    end
    
    % Display that x0 was shifted in order to honor bounds
    if shiftedX0
        if verbosity >= 3
            if strcmpi(OUTPUT.algorithm,interiorPoint) 
                fprintf(getString(message('optimlib:fmincon:ShiftX0StrictInterior')));
                fprintf('\n');
            else
                fprintf(getString(message('optimlib:fmincon:ShiftX0ToBnds')));
                fprintf('\n');
            end
        end
    end
        
    % Evaluate function
    initVals.g = zeros(sizes.nVar,1);
    HESSIAN = []; 
    
    switch funfcn{1}
    case 'fun'
       try
          initVals.f = feval(funfcn{3},X,varargin{:});
       catch userFcn_ME
            optim_ME = MException('optimlib:fmincon:ObjectiveError', ...
                getString(message('optimlib:fmincon:ObjectiveError')));
            userFcn_ME = addCause(userFcn_ME,optim_ME);
            rethrow(userFcn_ME)
       end
    case 'fungrad'
       try
          [initVals.f,initVals.g] = feval(funfcn{3},X,varargin{:});
       catch userFcn_ME
            optim_ME = MException('optimlib:fmincon:ObjectiveError', ...
                getString(message('optimlib:fmincon:ObjectiveError')));
            userFcn_ME = addCause(userFcn_ME,optim_ME);
            rethrow(userFcn_ME)
       end
    case 'fungradhess'
       try
          [initVals.f,initVals.g,HESSIAN] = feval(funfcn{3},X,varargin{:});
       catch userFcn_ME
            optim_ME = MException('optimlib:fmincon:ObjectiveError', ...
                getString(message('optimlib:fmincon:ObjectiveError')));
            userFcn_ME = addCause(userFcn_ME,optim_ME);
            rethrow(userFcn_ME)
       end
    case 'fun_then_grad'
       try
          initVals.f = feval(funfcn{3},X,varargin{:});
       catch userFcn_ME
            optim_ME = MException('optimlib:fmincon:ObjectiveError', ...
                getString(message('optimlib:fmincon:ObjectiveError')));
            userFcn_ME = addCause(userFcn_ME,optim_ME);
            rethrow(userFcn_ME)
       end
       try
          initVals.g = feval(funfcn{4},X,varargin{:});
       catch userFcn_ME
            optim_ME = MException('optimlib:fmincon:GradientError', ...
                getString(message('optimlib:fmincon:GradientError')));
            userFcn_ME = addCause(userFcn_ME,optim_ME);
            rethrow(userFcn_ME)
       end
    case 'fun_then_grad_then_hess'
       try
          initVals.f = feval(funfcn{3},X,varargin{:});
       catch userFcn_ME
            optim_ME = MException('optimlib:fmincon:ObjectiveError', ...
                getString(message('optimlib:fmincon:ObjectiveError')));
            userFcn_ME = addCause(userFcn_ME,optim_ME);
            rethrow(userFcn_ME)
       end
       try
          initVals.g = feval(funfcn{4},X,varargin{:});
       catch userFcn_ME
            optim_ME = MException('optimlib:fmincon:GradientError', ...
                getString(message('optimlib:fmincon:GradientError')));
            userFcn_ME = addCause(userFcn_ME,optim_ME);
            rethrow(userFcn_ME)
       end
       try
          HESSIAN = feval(funfcn{5},X,varargin{:});
       catch userFcn_ME
            optim_ME = MException('optimlib:fmincon:HessianError', ...
                getString(message('optimlib:fmincon:HessianError')));            
            userFcn_ME = addCause(userFcn_ME,optim_ME);
            rethrow(userFcn_ME)
       end
    otherwise
       error(message('optimlib:fmincon:UndefinedCallType'));
    end
    
    % Check that the objective value is a scalar
    if numel(initVals.f) ~= 1
       error(message('optimlib:fmincon:NonScalarObj'))
    end
    
    % Check that the objective gradient is the right size
    initVals.g = initVals.g(:);
    if numel(initVals.g) ~= sizes.nVar
       error('optimlib:fmincon:InvalidSizeOfGradient', ...
           getString(message('optimlib:commonMsgs:InvalidSizeOfGradient',sizes.nVar)));
    end
    
    % Evaluate constraints
    switch confcn{1}
    case 'fun'
        try
            [ctmp,ceqtmp] = feval(confcn{3},X,varargin{:});
        catch userFcn_ME
            if strcmpi('MATLAB:maxlhs',userFcn_ME.identifier)
                    error(message('optimlib:fmincon:InvalidHandleNonlcon'))
            else
                optim_ME = MException('optimlib:fmincon:NonlconError', ...
                    getString(message('optimlib:fmincon:NonlconError')));
                userFcn_ME = addCause(userFcn_ME,optim_ME);
                rethrow(userFcn_ME)
            end
        end
        initVals.ncineq = ctmp(:);
        initVals.nceq = ceqtmp(:);
        initVals.gnc = zeros(sizes.nVar,length(initVals.ncineq));
        initVals.gnceq = zeros(sizes.nVar,length(initVals.nceq));
    case 'fungrad'
       try
          [ctmp,ceqtmp,initVals.gnc,initVals.gnceq] = feval(confcn{3},X,varargin{:});
       catch userFcn_ME
           optim_ME = MException('optimlib:fmincon:NonlconError', ...
               getString(message('optimlib:fmincon:NonlconError')));           
           userFcn_ME = addCause(userFcn_ME,optim_ME);
           rethrow(userFcn_ME)
       end
       initVals.ncineq = ctmp(:);
       initVals.nceq = ceqtmp(:);
    case 'fun_then_grad'
        try
            [ctmp,ceqtmp] = feval(confcn{3},X,varargin{:});
        catch userFcn_ME
            optim_ME = MException('optimlib:fmincon:NonlconError', ...
                getString(message('optimlib:fmincon:NonlconError')));
            userFcn_ME = addCause(userFcn_ME,optim_ME);
            rethrow(userFcn_ME)
        end
        initVals.ncineq = ctmp(:);
        initVals.nceq = ceqtmp(:);
        try
            [initVals.gnc,initVals.gnceq] = feval(confcn{4},X,varargin{:});
        catch userFcn_ME
            optim_ME = MException('optimlib:fmincon:NonlconFunOrGradError', ...
                getString(message('optimlib:fmincon:NonlconFunOrGradError')));
            userFcn_ME = addCause(userFcn_ME,optim_ME);
            rethrow(userFcn_ME)
        end
    case ''
       % No nonlinear constraints. Reshaping of empty quantities is done later
       % in this file, where both cases, (i) no nonlinear constraints and (ii)
       % nonlinear constraints that have one type missing (equalities or
       % inequalities), are handled in one place
       initVals.ncineq = [];
       initVals.nceq = [];
       initVals.gnc = [];
       initVals.gnceq = [];
    otherwise
       error(message('optimlib:fmincon:UndefinedCallType'));
    end
    
    % Check for non-double data typed values returned by user functions 
    if ~isempty( isoptimargdbl('FMINCON', {'f','g','H','c','ceq','gc','gceq'}, ...
       initVals.f, initVals.g, HESSIAN, initVals.ncineq, initVals.nceq, initVals.gnc, initVals.gnceq) )
        error('optimlib:fmincon:NonDoubleFunVal',getString(message('optimlib:commonMsgs:NonDoubleFunVal','FMINCON')));
    end
    
    sizes.mNonlinEq = length(initVals.nceq);
    sizes.mNonlinIneq = length(initVals.ncineq);
    
    % Make sure empty constraint and their derivatives have correct sizes (not 0-by-0):
    if isempty(initVals.ncineq)
        initVals.ncineq = reshape(initVals.ncineq,0,1);
    end
    if isempty(initVals.nceq)
        initVals.nceq = reshape(initVals.nceq,0,1);
    end
    if isempty(initVals.gnc)
        initVals.gnc = reshape(initVals.gnc,sizes.nVar,0);
    end
    if isempty(initVals.gnceq)
        initVals.gnceq = reshape(initVals.gnceq,sizes.nVar,0);
    end
    [cgrow,cgcol] = size(initVals.gnc);
    [ceqgrow,ceqgcol] = size(initVals.gnceq);
    
    if cgrow ~= sizes.nVar || cgcol ~= sizes.mNonlinIneq
       error(message('optimlib:fmincon:WrongSizeGradNonlinIneq', sizes.nVar, sizes.mNonlinIneq))
    end
    if ceqgrow ~= sizes.nVar || ceqgcol ~= sizes.mNonlinEq
       error(message('optimlib:fmincon:WrongSizeGradNonlinEq', sizes.nVar, sizes.mNonlinEq))
    end
    
    if diagnostics
       % Do diagnostics on information so far
       diagnose('fmincon',OUTPUT,flags.grad,flags.hess,flags.constr,flags.gradconst,...
          XOUT,sizes.mNonlinEq,sizes.mNonlinIneq,lin_eq,lin_ineq,l,u,funfcn,confcn);
    end
    
    % Create default structure of flags for finitedifferences:
    % This structure will (temporarily) ignore some of the features that are
    % algorithm-specific (e.g. scaling and fault-tolerance) and can be turned
    % on later for the main algorithm.
    finDiffFlags.fwdFinDiff = strcmpi(options.FinDiffType,'forward');
    finDiffFlags.scaleObjConstr = false; % No scaling for now
    finDiffFlags.chkFunEval = false;     % No fault-tolerance yet
    finDiffFlags.chkComplexObj = false;  % No need to check for complex values
    finDiffFlags.isGrad = true;          % Scalar objective
    
    % Check derivatives
    if derivativeCheck && ...               % User wants to check derivatives...
       (flags.grad || ...                   % of either objective or ...
       flags.gradconst && sizes.mNonlinEq+sizes.mNonlinIneq > 0) % nonlinear constraint function.
        validateFirstDerivatives(funfcn,confcn,X, ...
            l,u,options,finDiffFlags,sizes,varargin{:});
    end
    
    % call algorithm
    if strcmpi(OUTPUT.algorithm,activeSet) % active-set
        defaultopt.MaxIter = 400; defaultopt.MaxFunEvals = '100*numberofvariables'; defaultopt.TolX = 1e-6;
        defaultopt.Hessian = 'off';
        problemInfo = []; % No problem related data
        [X,FVAL,LAMBDA,EXITFLAG,OUTPUT,GRAD,HESSIAN]=...
            nlconst(funfcn,X,l,u,full(A),B,full(Aeq),Beq,confcn,options,defaultopt, ...
            finDiffFlags,verbosity,flags,initVals,problemInfo,optionFeedback,varargin{:});
    elseif strcmpi(OUTPUT.algorithm,trustRegionReflective) % trust-region-reflective
       if (strcmpi(funfcn{1}, 'fun_then_grad_then_hess') || strcmpi(funfcn{1}, 'fungradhess'))
          Hstr = [];
       elseif (strcmpi(funfcn{1}, 'fun_then_grad') || strcmpi(funfcn{1}, 'fungrad'))
          n = length(XOUT); 
          Hstr = optimget(options,'HessPattern',defaultopt,'fast');
          if ischar(Hstr) 
             if strcmpi(Hstr,'sparse(ones(numberofvariables))')
                Hstr = sparse(ones(n));
             else
                error(message('optimlib:fmincon:InvalidHessPattern'))
             end
          end
          checkoptionsize('HessPattern', size(Hstr), n);
       end
       
       defaultopt.MaxIter = 400; defaultopt.MaxFunEvals = '100*numberofvariables'; defaultopt.TolX = 1e-6;
       defaultopt.Hessian = 'off';
       % Trust-region-reflective algorithm does not compute constraint
       % violation as it progresses. If the user requests the output structure,
       % we need to calculate the constraint violation at the returned
       % solution.
       if nargout > 3
           computeConstrViolForOutput = true;
       else
           computeConstrViolForOutput = false;
       end
    
       if isempty(Aeq)
          [X,FVAL,LAMBDA,EXITFLAG,OUTPUT,GRAD,HESSIAN] = ...
             sfminbx(funfcn,X,l,u,verbosity,options,defaultopt,computeLambda,initVals.f,initVals.g, ...
             HESSIAN,Hstr,flags.detailedExitMsg,computeConstrViolForOutput,optionFeedback,varargin{:});
       else
          [X,FVAL,LAMBDA,EXITFLAG,OUTPUT,GRAD,HESSIAN] = ...
             sfminle(funfcn,X,sparse(Aeq),Beq,verbosity,options,defaultopt,computeLambda,initVals.f, ...
             initVals.g,HESSIAN,Hstr,flags.detailedExitMsg,computeConstrViolForOutput,optionFeedback,varargin{:});
       end
    elseif strcmpi(OUTPUT.algorithm,interiorPoint)
        defaultopt.MaxIter = 1000; defaultopt.MaxFunEvals = 3000; defaultopt.TolX = 1e-10;
        defaultopt.Hessian = 'bfgs';
        mEq = lin_eq + sizes.mNonlinEq + nnz(xIndices.fixed); % number of equalities
        % Interior-point-specific options. Default values for lbfgs memory is 10, and 
        % ldl pivot threshold is 0.01
        options = getIpOptions(options,sizes.nVar,mEq,flags.constr,defaultopt,10,0.01); 
    
        [X,FVAL,EXITFLAG,OUTPUT,LAMBDA,GRAD,HESSIAN] = barrier(funfcn,X,A,B,Aeq,Beq,l,u,confcn,options.HessFcn, ...
            initVals.f,initVals.g,initVals.ncineq,initVals.nceq,initVals.gnc,initVals.gnceq,HESSIAN, ...
            xIndices,options,optionFeedback,finDiffFlags,varargin{:});
    else % sqp
        defaultopt.MaxIter = 400; defaultopt.MaxFunEvals = '100*numberofvariables'; 
        defaultopt.TolX = 1e-6; defaultopt.Hessian = 'bfgs';
        % Validate options used by sqp
        options = getSQPOptions(options,defaultopt,sizes.nVar);
        optionFeedback.detailedExitMsg = flags.detailedExitMsg;
        % Call algorithm
        [X,FVAL,EXITFLAG,OUTPUT,LAMBDA,GRAD,HESSIAN] = sqpLineSearch(funfcn,X,full(A),full(B),full(Aeq),full(Beq), ...
            full(l),full(u),confcn,initVals.f,full(initVals.g),full(initVals.ncineq),full(initVals.nceq), ...
            full(initVals.gnc),full(initVals.gnceq),xIndices,options,finDiffFlags,verbosity,optionFeedback,varargin{:});
    end
    

     

    展开全文
  • main函数的参数解析

    千次阅读 2018-06-04 20:22:43
    其实main函数也是有参数的。 int main(int argc,char* argv[],char* envp[]) 那么这三个参数分别代表什么含义呢? 第一个参数:argc是个整数变量,表示命令行参数的个数(含第一个参数)。 第二个参数:argv是...

    其实main函数也是有参数的。

    int main(int argc,char* argv[],char* envp[])

    那么这三个参数分别代表什么含义呢?

    第一个参数:argc是个整数变量,表示命令行参数的个数(含第一个参数)。

    第二个参数:argv是个字符指针的数组,每个元素是一个字符指针,指向一个字符串。这些字符串就是命令行中的每一个参数(字符串)。

    第三个参数:envp是字符指针的数组,数组的每一个原元素是一个指向一个环境变量(字符串)的字符指针。

     

    接下来我们就利用main函数的这三个参数来实现一个简单的整数计算器。

    该程序呢,可以接受三个参数,第一个参数“-a”选项执行加法,“-s”选项执行减法,“-m”选项执行乘法,“-d”选项执行除法,后面两个参数为操作数。

    实现代码如下:

    #include <stdio.h>
    #include <windows.h>
    #include <stdlib.h>  //atoi函数的头文件
    
    int Add(int x, int y)  //加法
    {
        return x + y;
    }
    
    int Sub(int x, int y)  //减法
    {
        return x - y;
    }
    
    int Mul(int x, int y)  //乘法
    {
        return x * y;
    }
    
    int Div(int x, int y)  //除法
    {
        return x / y;
    }
    
    int main(int argc, char *argv[])//main函数的参数
    {
        int x = 0;
        int y = 0;
        int ret = 0;
    
        if (argc != 4) //如果有效参数个数不是4个,就报错
        {
            printf("参数错误!\n");
            return 1;
        }
    
        x = atoi (argv[2]);// int atoi(const char* nptr)
        y = atoi (argv[3]); //atoi 把字符串转换成整型数
    
    
        if (*argv[1] == '-') 
        {
            switch (*(argv[1]+1))
            {
            case 'a':
                ret = Add(x, y);
                break;
            case 's':
                ret = Sub(x, y);
                break;
            case 'm':
                ret = Mul(x, y);
                break;
            case 'd':
                ret = Div(x, y);
                break;
            default:
                printf("参数错误!\n");
                break;
            }
    
            printf("ret = %d\n", ret);
        }
    
        system("pause");//便于观察
        return 0;
    }

    运行这个程序有两种方法: 

    ①打开解决方法,右击工程名,选择“属性”,在“调试”中找到“命令行参数”,在里面输入“-a 11 22”,然后直接运行这个程序 

    如下图:

     

    运行结果如下:

    ②在cmd窗口,用cd命令进入你的工程文件的Debug目录下,然后输入你的项目名+“-a 11 22”

    图示如下:

    以上我们就实现了利用main函数的参数来简单模拟一个计算器,你学会了么?

     

    展开全文
  • 主要内容:复数与复变函数解析函数、复变函数的积分、级数、留数、保形映射、积分变换等。 一、复数基本知识 1.1 复数基本概念 对任意两实数x, y,称z=x+iyz=x+iyz=x+iy或z=x+yiz=x+yiz=x+yi为复数,其中i2=−1i^...

    实变函数(高等数学)主要内容:

    • 微积分(一元、二元、多元)
    • 级数理论
    • 常微分方程

    复变函数:

    • 研究对象:自变量为复数的函数
    • 主要任务:研究复变数之间的相互依赖关系,具体地就是复数域上的微积分
    • 主要内容:复数与复变函数、解析函数、复变函数的积分、级数、留数、保形映射、积分变换等。

    一、复数基本知识

    1.1 复数基本概念

    对任意两实数x, y,称z=x+iyz=x+iyz=x+yiz=x+yi为复数,其中i2=1i^2=-1,i称为虚部

    复数z的实部Re(z)=x,虚部Im(z)=y

    复数的模:z=x2+y20|z|=\sqrt{x^2+y^2}\ge0

    复数相等:z1=z2    x1=x2,y1=y2z_1=z_2 \iff x_1=x_2,y_1=y_2,其中z1=x1+iy1,z2=x2+iy2z_1=x_1+iy_1,z_2=x_2+iy_2

    z=0    Re(z)=Im(z)=0z=0\iff Re(z)=Im(z)=0

    一般两个复数不能比较大小。

    1.2 共轭复数

    z=x+iyz=x+iy,称z=xiy\overline{z}=x-iy为z的共轭复数。

    1.3 几何表示

    1.3.1 可以用点来表示:

    z=x+iy    z=x+iy \iff复平面上的点P(x,y)P(x,y)
    复平面上横坐标轴称为实轴,纵坐标轴称为虚轴。

    1.3.2 可以用向量来表示:

    z=x+iy    P(x,y)    OP={x,y}z=x+iy\iff P(x,y)\iff \overrightarrow{OP}=\{x,y\}
    可以用向量OP\overrightarrow{OP}来表示z=x+iyz=x+iy
    复数的模:向量的长度z=OP=x2+y2|z|=|\overrightarrow{OP}|=\sqrt{x^2+y^2}
    复数的幅角:向量与正实轴之间的夹角θ=Argz=(OP,x)\theta=Arg_z=(\overrightarrow{OP},x)
    tan(Argz)=yxtan(Argz)={y\over x}
    当z=0时,幅角无意义
    幅角是无穷多的:Argz=θ=θ0+2kπArg_z=\theta=\theta_0+2k\pi
    满足π<θ0<π-\pi<\theta_0<\piθ0\theta_0称为幅角ArgzArg_z的主值,记作:θ0=Argz\theta_0=Arg_z

    1.3.3 可以用三角来表示:

    用复数的模与幅角来表示非零复数z
    {x=rcosθy=rsinθ\begin{cases}x=rcos\theta\\y=rsin\theta\end{cases}得:
    z=r(cosθ+isinθ)z=r(cos\theta+isin\theta)

    1.3.4 用指数表示

    由欧拉公式:eiθ=cosθ+isinθe^{i\theta}=cos\theta+isin\theta可得非零复数z的指数表达式:
    z=reiθz=re^{i\theta}

    1.2 复数的乘幂与方根

    1.2.1 复数的乘积与熵

    利用复数的三角表示,我们可以更简单的表示复数的乘法与除法:
    定理:设z1,z2z_1,z_2是两个非零复数:
    z1=z1(cosArgz1+isinArgz1)=z1ei(Argz1)z_1=|z_1|(cosArg_{z_1}+isinArg_{z_1})=|z_1|e^{i(Argz_1)}
    z2=z2(cosArgz2+isinArgz2)=z2ei(Argz2)z_2=|z_2|(cosArg_{z_2}+isinArg_{z_2})=|z_2|e^{i(Argz_2)}

    则:
    z1z2=z1z2,Arg(z1z2)=Arg(z1)+Arg(z2)|z_1z_2|=|z_1||z_2|,Arg(z_1z_2)=Arg(z_1)+Arg(z_2)
    z1z2=z1z2(z20),Arg(z1z2)=Arg(z1)Arg(z2)|{z_1\over z_2}|={|z_1|\over|z_2|}(z_2\ne0),Arg({z_1\over z_2)}=Arg(z_1)-Arg(z_2)

    乘法的几何意义:将复数z1z_1按逆时针方向旋转一个角度Arg(z_2),再将其伸缩到|z_2|倍。

    1.2.2 复数的乘幂

    n个相同复数z的乘积称为z的n次幂:znz^n
    zn=zz...z=rneinθ=rn(cosnθ+isinnθ)z^n=zz...z=r^ne^{in\theta}=r^n(cosn\theta+isinn\theta)
    特别地:当z=r=1|z|=r=1时,zn=(cosnθ+isinnθ)z^n=(cosn\theta+isinn\theta),此时有:
    (cosθ+isinθ)n=cosnθ+isinnθ(cos\theta+isin\theta)^n=cosn\theta+isinn\theta
    这个公式称为De Moivre公式

    zn=1znz^{-n}={1\over z^n},则:
    zn=rn(cos(nθ)+isin(nθ))=rneinθz^{-n}=r^{-n}(cos(-n\theta)+isin(-n\theta))=r^{-n}e^{-in\theta}

    1.2.3 复数的方根

    z=reiθz=re^{i\theta}为已知复数,n为正整数,则称满足方程wn=zw^n=z的所有w值为z的n次方根,记为w=znw=\sqrt[n]{z}
    在这里插入图片描述
    在这里插入图片描述

    https://wenku.baidu.com/view/95266a772e60ddccda38376baf1ffc4ffe47e29a.html

    二、欧拉公式:

    i=1i=\sqrt{-1},欧拉公式为:
    eix=cosx+isinxe^{ix}=cosx+isinx

    欧拉公式的推导用到了泰勒展开,至于eixe^{ix}为什么可以泰勒展开需要证明,这里忽略:

    eix=1+ix+(ix)22!+(ix)33+(ix)44!+(ix)55!+(ix)66!+...e^{ix}=1+ix+{(ix)^2\over 2!}+{(ix)^3\over 3}+{(ix)^4\over 4!}+{(ix)^5\over 5!}+{(ix)^6\over 6!}+...
    =1+ixx22!ix33!+x44!+ix55!x66!\quad=1+ix-{x^2\over2!}-{ix^3\over3!}+{x^4\over4!}+{ix^5\over5!}-{x^6\over6!}
    =(1x22!+x44!x66!+...)+i(xx33!+x55!...)\quad=(1-{x^2\over2!}+{x^4\over4!}-{x^6\over6!}+...)+i(x-{x^3\over3!}+{x^5\over5!}-...)
    =cosx+isinx\quad=cosx+isinx

    欧拉公式的一个变形:
    eix=cosx+isinxe^{ix}=cosx+isinx

    eix=cosxisinxe^{-ix}=cosx-isinx

    相加相减可以得到:

    sinx=eixeix2isinx={e^{ix}-e{-ix}\over 2i}

    cosx=eix+eix2cosx={e^{ix}+e^{-ix}\over2}

    三、复变函数的导数

    3.1 导数的定义

    在这里插入图片描述
    在这里插入图片描述

    3.2 求导公式与法则(实函数中求导法则的推广)

    1. 常数的导数c=(a+ib)=0c'=(a+ib)'=0
    2. (zn)=nzn1(z^n)'=nz^{n-1}(n是自然数)
    3. 设函数f(z),g(z)f(z),g(z)均可导,则:
      [f(z)±g(z)]=f(z)±g(z)[f(z)\pm g(z)]'=f'(z)\pm g'(z)
      [f(z)g(z)]=f(z)g(z)+f(z)g(z)[f(z)g(z)]'=f'(z)g(z)+f(z)g'(z)
      [f(z)g(z)]=f(z)g(z)f(z)g(z)g2(z)(g(z)0)[{f(z)\over g(z)}]'={f'(z)g(z)-f(z)g'(z)\over g^2(z)}\quad(g(z)\ne0)
    4. 复合函数的导数:f[g(z)]=f(g(z))g(z)f[g(z)]'=f'(g(z))g'(z)
    5. 反函数的导数:f(z)=1ϕ(w)f'(z)={1\over \phi'(w)},其中:w=f(z)w=f(z),与z=ϕ(w)z=\phi(w)互为单值的反函数,且ϕ(w)0\phi'(w)\ne0

    在这里插入图片描述
    在这里插入图片描述
    注意:

    1. 复变函数在一点处可导,要比实函数在一点处可导要求高得多,也复杂得多,这是因为z0\triangle z\to0是在平面区域上以任意方式趋于零的缘故。
    2. 在高等数学中要举出一个处处连续,但处处不可导的例题是狠苦难的,但在复变函数中,却轻而易举

    3.3 可导与连续

    在这里插入图片描述

    四、解析函数

    4.1 定义

    在这里插入图片描述
    在这里插入图片描述

    4.2 定理

    在这里插入图片描述
    在这里插入图片描述

    4.3 解析函数的充要条件

    在这里插入图片描述

    https://wenku.baidu.com/view/532c39681eb91a37f1115c77.html
    复变函数基本初等函数

    展开全文
  • Java之函数式接口源码解析

    千次阅读 2020-09-28 20:23:17
    我们可以在一个接口上使用 @FunctionalInterface注解,这样做可以检查它是否是一个函数式接口。同时 javadoc 也会包含一条声明,说明这个接口是一个函数式接口。 在java.util.function包下定义了Java 8 的丰富的函数...

    函数式接口

    只包含一个抽象方法的接口,称为函数式接口。

    你可以通过 Lambda 表达式来创建该接口的对象。(若 Lambda 表达式抛出一个受检异常(即:非运行时异常),那么该异常需要在目标接口的抽象方法上进行声明)。

    我们可以在一个接口上使用 @FunctionalInterface注解,这样做可以检查它是否是一个函数式接口。同时 javadoc 也会包含一条声明,说明这个接口是一个函数式接口。

    java.util.function包下定义了Java 8 的丰富的函数式接口

    image-20200923165329350

    我们查看Comparator接口源码。发现了一些矛盾的地方。

    image-20200923165757180

    我们发现了该接口中不止包含了一个方法,还存在大量的defaultstatic方法。这和上文的定义是矛盾的!!

    在jdk8之前,interface之中可以定义变量和方法,变量必须是public、static、final的,方法必须是public、abstract的。由于这些修饰符都是默认的,JDK8及以后,允许我们在接口中定义static方法和default方法。

    JDK8接口中的静态方法和默认方法,都不算是抽象方法。。接口默认继承java.lang.Object,所以如果接口显示声明覆盖了Object中方法,那么也不算抽象方法。

    image-20200923170228916

    所以该接口的确是一个函数式接口!!

    Java从诞生日起就是一直倡导“一切皆对象”,在Java里面面向对象(OOP) 编程是一切。但是随着python、scala等语言的兴起和新技术的挑战,Java不 得不做出调整以便支持更加广泛的技术要求,也即java不但可以支持OOP还 可以支持OOF(面向函数编程)

    在函数式编程语言当中,函数被当做一等公民对待。在将函数作为一等公民的 编程语言中,Lambda表达式的类型是函数。但是在Java8中,有所不同。在 Java8中,Lambda表达式是对象,而不是函数,它们必须依附于一类特别的 对象类型——函数式接口。

    简单的说,在Java8中,Lambda表达式就是一个函数式接口的实例。这就是 Lambda表达式和函数式接口的关系。也就是说,只要一个对象是函数式接口 的实例,那么该对象就可以用Lambda表达式来表示。

    所以以前用匿名实现类表示的现在都可以用Lambda表达式来写。

    **@**FunctionalInterface

    image-20200923170602530

    1. 该注解只能标记在"有且仅有一个抽象方法"的接口上。

    2. JDK8接口中的静态方法和默认方法,都不算是抽象方法。

    3. 接口默认继承java.lang.Object,所以如果接口显示声明覆盖了Object中方法,那么也不算抽象方法。

    4. 该注解不是必须的,如果一个接口符合"函数式接口"定义,那么加不加该注解都没有影响。加上该注解能够更好地让编译器进行检查。如果编写的不是函数式接口,但是加上了@FunctionInterface,那么编译器会报错。

    自定义函数式接口

    通过对函数式接口概念的认知,我们现在来自定义一个MyFunctionInterface 函数式接口测试。

    只包含一个抽象方法

    image-20200923171412859

    //自定义函数式接口
    public interface MyFunctionInterface<T> {
    
        //抽象方法
        T test(T t);
    }
    

    测试类TestFunction

    image-20200923171514395

    public class TestFunction {
    
        public static void main(String[] args) {
            MyFunctionInterface<String> function = (str) -> {
                return str;
            };
    
            System.out.println(function.test("FunctionInterface Test!"));
        }
    }
    

    包含一个覆盖Object方法

    覆盖Object的 hashCode方法

    image-20200923171729178

    再次运行测试类,成功!说明它是一个函数式接口

    image-20200923171514395

    //自定义函数式接口
    public interface MyFunctionInterface<T> {
    
        //抽象方法
        T test(T t);
    
        //覆盖Object方法
        int hashCode();
        
    }
    

    包含一个default方法

    image-20200923172018308

    //自定义函数式接口
    public interface MyFunctionInterface<T> {
    
        //抽象方法
        T test(T t);
    
        //覆盖Object方法
        int hashCode();
    
        //默认方法
        public default void defaultMethod(){
    
        }
    
    }
    

    再次运行测试类,成功!说明它default不是抽象方法,该接口是一个函数式接口

    image-20200923171514395

    包含一个static方法

    image-20200923185337449

    public interface MyFunctionInterface<T> {
    
        //抽象方法
        T test(T t);
    
        //覆盖Object方法
        int hashCode();
    
        //默认方法
        public default void defaultMethod(){
    
        }
    
        //静态方法
        public static void staticMethod(){
    
        }
    }
    

    再次运行测试类,成功!说明它static不是抽象方法,该接口是一个函数式接口

    image-20200923171514395

    标注@FunctionInterface注解

    通过前面的测试,我们可以明确知道,只要该接口只含有一个抽象方法,它就是一个函数式接口。而不是一定要标注@FunctionInterface注解,这两者之间没有绝对的联系。

    该注解不是必须的,如果一个接口符合"函数式接口"定义,那么加不加该注解都没有影响。加上该注解能够更好地让编译器进行检查。如果编写的不是函数式接口,但是加上了@FunctionInterface,那么编译器会报错。

    image-20200923185744315

    //自定义函数式接口
    @FunctionalInterface
    public interface MyFunctionInterface<T> {
    
        //抽象方法
        T test(T t);
    
        //覆盖Object方法
        int hashCode();
    
        //默认方法
        public default void defaultMethod(){
    
        }
    
        //静态方法
        public static void staticMethod(){
    
        }
    }
    

    四大核心函数式接口

    函数式接口 参数类型 返回类型 用途
    Consumer<T>消费型 T void 对类型为T的对象应用操作,包含方法:void accept(T t)
    Supplier<T>供给型 T 对类型为T的对象,包含方法:T get()
    Function<T,R>函数型 T R 对类型为T的对象应用操作,并返回结果。结果是R类型的对象。包含方法:R apply(T t)
    Predicate<T>断定型 T boolean 确定类型为T的对象是否满足某约束,并返回boolean值。包含方法boolean test(T t)

    Consumer消费型

    image-20200923192317870

    @Test
    public void test1(){
    
        happyTime(500, new Consumer<Double>() {
            @Override
            public void accept(Double aDouble) {
                System.out.println("学习太累了,去天上人间买了瓶矿泉水,价格为:" + aDouble);
            }
        });
    
        System.out.println("********************");
    
        happyTime(400,money -> System.out.println("学习太累了,去天上人间喝了口水,价格为:" + money));
    }
    
    public void happyTime(double money, Consumer<Double> con){
        con.accept(money);
    }
    

    image-20200923192400600

    Supplier供给型

    image-20200923193152964

    @Test
    public void test2() {
    
        System.out.println(get(new Supplier<String>() {
            @Override
            public String get() {
                return "犯罪人:张三";
            }
        }));
    
        System.out.println(get(() -> {
            return "法外狂徒三哥!";
        }));
    }
    
    public String get(Supplier<String> supplier) {
        return supplier.get();
    }
    

    image-20200923193220508

    Function函数型接口

    image-20200923193912896

    @Test
    public void test3() {
        System.out.println(getLength("test", new Function<String, Integer>() {
            @Override
            public Integer apply(String s) {
                return s.length();
            }
        }));
    
        System.out.println(getLength("lambda", str -> str.length()));
    }
    
    public int getLength(String s, Function<String, Integer> function) {
        return function.apply(s);
    }
    

    image-20200923193957077

    Predicate断定型接口

    image-20200923194231733

    @Test
    public void test4() {
        List<String> list = Arrays.asList("北京", "南京", "天津", "东京", "西京", "普京");
    
        List<String> filterStrs = filterString(list, new Predicate<String>() {
            @Override
            public boolean test(String s) {
                return s.contains("津");
            }
        });
    
        System.out.println(filterStrs);
    
    
        List<String> filterStrs1 = filterString(list, s -> s.contains("京"));
        System.out.println(filterStrs1);
    }
    
    //根据给定的规则,过滤集合中的字符串。此规则由Predicate的方法决定
    public List<String> filterString(List<String> list, Predicate<String> pre) {
    
        ArrayList<String> filterList = new ArrayList<>();
    
        for (String s : list) {
            if (pre.test(s)) {
                filterList.add(s);
            }
        }
    
        return filterList;
    
    }
    

    image-20200923194305931

    其他接口

    函数式接口 参数类型 返回类型 用途
    BiFunction<T, U, R> T, U R 对类型为 T, U 参数应用操作,返回 R 类型的结 果。包含方法为: R apply(T t, U u);
    UnaryOperator (Function子接口) T T 对类型为T的对象进行一元运算,并返回T类型的 结果。包含方法为:T apply(T t);
    BinaryOperator (BiFunction 子接口) T, T T 对类型为T的对象进行二元运算,并返回T类型的 结果。包含方法为: T apply(T t1, T t2);
    BiConsumer<T, U> T, U void 对类型为T, U 参数应用操作。 包含方法为: void accept(T t, U u)
    BiPredicate<T,U> T,U boolean 包含方法为: boolean test(T t,U u)
    ToIntFunction< T > ToLongFunction< T > ToDoubleFunction< T > T int long double 分别计算int、long、double值的函数
    IntFunction< R > LongFunction< R > DoubleFunction< R > int long double R 参数分别为int、long、double 类型的函数

    image-20200923194851914

    展开全文
  • hash函数解析

    千次阅读 2011-12-01 16:31:31
    Hash函数在多个领域均有应用,而在数字签名和数据库实现时又的最多,比如基于hash的索引,是最好的单值查找索引; 同时,在当前数据爆炸的场景下,执行相似item的查找时,在内存受限时,均可以采取LSH(local ...
  • 布尔函数敏感度是一个困扰学界多年的问题,甚至有很多科学家在听说这个猜想被证明后,以为证明会非常繁锁,甚至直接打算几周来学习,但是看到论文后又惊叹于作者论证方式的巧妙,而纷纷点赞。而从网上的资料来看...
  • 正弦交流电三要素表示方法:解析法、正弦曲线法、旋转矢量法解析法解析法数学公式表述正弦交流电与实践变化关系的方法。公式如下:e=Emsin(ωt+Φe)u=Umsin(ωt+Φu)i=Imsin(ωt+Φi)它可以表达正弦量的...
  • 复变函数与积分变换系列(一) - 复变函数解析函数 Author : Benjamin142857 [TOC] 0 .几个基本概念 实虚部 Plural:&amp;nbsp;&amp;nbsp;&amp;nbsp;z=x+iyReal:&amp;nbsp;&amp...
  • Kotlin扩展函数与重载操作符解析

    千次阅读 2017-06-15 17:58:06
    扩展函数可以称为Kotlin的核心,标准库里到处充斥着扩展函数和高阶函数。然而标准库中扩展函数看起来是高深莫测,一脸懵逼。本文教你如何理解扩展函数
  • ARX函数解析

    千次阅读 2006-09-04 16:35:00
    这个函数用适当的默认值初始化给定的AcDbLayout对象。 AcApLayoutManager::setShowPageSetup函数 virtual void setShowPageSetup( Adesk::Boolean showPageSetupDlg) = 0; showPageSetupDlg 输入布尔值,“页面设置...
  • GPS从入门到放弃(二十六) --- RTKLIB函数解析

    千次阅读 多人点赞 2020-06-07 21:57:21
    此文中一些函数解析参考了 https://www.cnblogs.com/taqikema/p/8819798.html,在此表示感谢! 文章目录GPS从入门到放弃(二十六) --- RTKLIB函数解析rtksvrthreadrtkpospntpossatpossephclkeph2clksatpose
  • Tensorflow ActiveFunction激活函数解析

    千次阅读 2017-09-06 11:06:30
    觉得有用的话,欢迎一起讨论相互学习~Follow MeTensorflow提供了多种激活函数,在CNN中,人们主要是tf.nn.relu,是因为它虽然会带来一些信息损失,但是性能较为突出.开始设计模型时,推荐使用tf.nn.relu,但高级用户也可...
  •   解析法就是全部是已知量的式子来表达某个未知量。    数值法就是直接一个数值代入式子计算,看看等号或者不等号是否成立,不成立的话就调整代入式子的那个数。 2.解析分析和数值模拟 (1.2.这两个应该是...
  • VC++文件操作函数解析

    千次阅读 2012-08-29 16:50:08
    ftell:功 能:返回当前文件... 函数功能:函数 ftell() 用于得到文件位置指针当前位置相对于文件首的偏移字节数。在随机方式存取文件时,由于文件位置频繁的前后移动,程序不容易确定文件的当前位置。使用fseek函数
  • memset()函数解析及易错点

    千次阅读 2017-02-09 19:10:34
    memset()函数原型是extern void *memset(void *buffer, int c, int count) buffer:为指针或是数组, c:是赋给buffer的值, count:是buffer的长度.这个函数在socket中多用于清空数组.如:原型是memset(buffer, 0,...
  • matlab中的matchFeatures函数解析

    千次阅读 2018-10-15 21:49:14
    之前的号不用了,现在把以前的文章东西搬到这里(其实就一篇有点的) 之前在做特征匹配,matlab里面自带的matchFeatures说明文档写的其实挺明白的,奈何自己是个小白看不懂,所以上网查了查,再补上了点,有的部分...
  • 讨论中,我们主要以二元函数为主,因为从一元函数到二元函数会产生许多新问题,而从二元函数到二元以上的函数可以类推。 建议同学们在学习中,注意将二元函数的概念与结论与一元函数的相应的概念与结论加以比较,...
  • VBA解析JSON数据(1)-- Split函数

    千次阅读 2019-02-16 07:20:48
    JSON(JavaScript Object Notation) 是一种及其轻量级的数据交换格式,它是 ECMAScript (欧洲计算机协会制定的JavaScript规范)的一个子集,它使用完全独立于任何编程语言的文本格式来表示数据。 由于JSON天然具备了...
  • sklearn.linear_model.LogisticRegression()函数全称是Logistic回归(aka logit,MaxEnt)分类器。 class sklearn.linear_model.LogisticRegression(penalty='l2', dual=False, tol=0.0001, C=1.0, fit_intercept=...
  • 最近学习中碰到了以前学过的tf.nn.sigmoid_cross_entropy_with_logits()函数,特此记录。 tf.nn.sigmoid_cross_entropy_with_logits()函数用于计算交叉熵。 tf.nn.sigmoid_cross_entropy_with_logits( _sentinel=...
  • CserialPort类是基于多线程的,其工作流程如下:首先设置好串口参数,再开启串口检测工作线程,串口检测工作线程检测到串口接收到的数据、流控制事件或其他串口事件后,就以消息方式通知主程序,激发消息处理函数来...
  • 有理函数内插和外推算法实现

    千次阅读 2007-12-13 16:29:00
    算法名称:有理函数内插和外推 算法描述:Ri(i+1)...(i+m)表示过m+1个点(xi,yi)...(xi+m,yi+m)的有理函数。假定 (1)因为有μ+ν+1个未知的p和q(q0任意),则有 (2)在把插值函数定义为有理函数时,必须...
  • es6 javascript对象属性的简洁表示法

    千次阅读 2016-12-01 10:58:36
    ES6 允许直接写入变量和函数,作为对象的属性和方法。这样的书写更加简洁。var foo = 'bar'; var baz = {foo}; baz // {foo: "bar"} // 等同于 var baz = {foo: foo}; 上面代码表明, ES6 允许在对象之中...
  • 深度学习中Dropout原理解析

    万次阅读 多人点赞 2018-06-19 19:12:24
    1. Dropout简介1.1 Dropout出现的原因在机器学习的模型中,如果模型的参数太多,而训练样本又太少,训练出来的模型很容易产生过拟合的现象。...如果模型过拟合,那么得到的模型几乎不能。为了解决过拟合问题,一...
  • 本文介绍了大家熟知的梯度下降,还介绍了其它的优化方法,大家可以看到一些对比,和少量的公式推导,这篇博客主要来源于机器之心,链接已经给出,公式我推过了,没什么问题,最重要的是动笔推导,我把内容做了...
  • Hive2.1函数列表

    千次阅读 2018-06-07 10:32:34
    函数 运算符 函数 自带函数 用户自定义函数
  • 高斯过程可以被认为是一种机器学习算法,它利用点与点之间同质性的度量作为核函数,以从输入的训练数据预测未知点的值。本文从理论推导和实现详细地介绍了高斯过程,并在后面提供了它来近似求未知函数最优解的方法...
  • 目录 方法一:(一般方法) ...按照正常的思路,表示分段函数是在脚本文件里 if ..else..语句来完成,例如下列代码: function [y]=ch3_1(x) n=length(x); for i=1:n if x(i)>1 y(i)=x(i).^2; elseif ...
  • hive2.0中常的内置函数大全

    千次阅读 2018-12-09 00:29:05
    目录数学函数abs(x):返回绝对值greatest(T v1, T v2, ...):求最大值least(T v1, T v2, ...):求最小值round(DOUBLE a):四舍五入round(DOUBLE a, INT d):指定精度的四舍五入bround(DOUBLE a):银行家舍入bround...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 88,887
精华内容 35,554
关键字:

任何函数都可以用解析法表示