# About NMinimize with an array of variable

I was trying to test NMinimize on $$\int_0^1 (a+b(cx+d))^2 dx$$, then I guess it should be minimized when the integrand equals 0. It works fine when the integrand is only (a+bx)^2, I use the code:

z1[x_, y_] := y[[1]]*x + y[[2]] ;
Y = Table[y[i], {i, 1, 2}];
h[Y_] := Integrate[(z1[x, Y])^2, {x, 0, 1}]
NMinimize[h[Y], Y, AccuracyGoal -> 20, PrecisionGoal -> 18,
WorkingPrecision -> 40]


And I get the output :

{3.550736290059893672842701884381905283185*10^-144, {y[1] ->
6.527544368345474836762769419275328411033*10^-72,
y[2] -> -3.263772184172737418381384709637664205517*10^-72}}


But when I do the composition, I was confused, what I wrote is:

z1[x_, y_] := y[[1]]*x + y[[2]] ;
z2[x_, y_] := y[[3]]*x + y[[4]];
z[x_, y_] := z1@z2@x;
Y = Table[y[i], {i, 1, 4}];
h[Y_] := Integrate[(z[x, Y])^2, {x, 0, 1}];
NMinimize[h[Y], Y, AccuracyGoal -> 20, PrecisionGoal -> 18,
WorkingPrecision -> 40]



Where the $z[x,y]$ gives

y[[2]] + y[[1]] (x y[[3]] + y[[4]])


and $h[Y]$ gives

y[[2]]^2 + y[[1]] y[[2]] y[[3]] + 1/3 y[[1]]^2 y[[3]]^2 +
2 y[[1]] y[[2]] y[[4]] + y[[1]]^2 y[[3]] y[[4]] + y[[1]]^2 y[[4]]^2


which seem fine, but the result of NMinimize is :

NMinimize[
y[[2]]^2 + y[[1]] y[[2]] y[[3]] + 1/3 y[[1]]^2 y[[3]]^2 +
2 y[[1]] y[[2]] y[[4]] + y[[1]]^2 y[[3]] y[[4]] +
y[[1]]^2 y[[4]]^2, {y[1], y[2], y[3], y[4]}, AccuracyGoal -> 20,
PrecisionGoal -> 18, WorkingPrecision -> 40]


I dont know why I cannot get an answer from it, thanks for any help !

\$Version

(* "14.0.0 for Mac OS X ARM (64-bit) (December 13, 2023)" *)

Clear["Global*"]

z1[x_, y_List] := {x, 1} . y

Y = Array[y, 2];

h[y_List] := Integrate[z1[x, y]^2, {x, 0, 1}]

NMinimize[h[Y], Y]

(* {0., {y[1] -> 0., y[2] -> 0.}} *)


or

Minimize[h[Y], Y]

(* {0, {y[1] -> 0, y[2] -> 0}} *)

Y = Array[y, 4];


z1 must be given two arguments.

z[x_, y_List] := z1[z1[x, y[[{3, 4}]]], y[[{1, 2}]]]

h2[y_List] := Integrate[(z[x, y])^2, {x, 0, 1}];

NMinimize[h2[Y], Y]

(* {0., {y[1] -> -0.0000139272, y[2] -> -8.43686*10^-6,
y[3] -> -1.11022*10^-16, y[4] -> -0.605783}} *)


or

Minimize[h2[Y], Y]

(* {0, {y[1] -> -1, y[2] -> 0, y[3] -> 0, y[4] -> 0}} *)
`
• Thank you @Bob Hanlon , And I have a furthur question that here I composite two degree 1 function, if I want to also compare with constant composite degree two and degree two composite constant to get the best degree two approximation function( the sum of the degree of the two function is 2). How can I use for loop to do that ? (Because I want to actually graph the least square error between a given function here I use constant 0 and my composite approximation function to see how the error decreases with the sum of the degree of the two functions increase)
– 何子钦
Feb 12 at 21:38
• Do not ask new questions in comments. Post a new question with a concrete example, show what you have tried, and explain what problems you are having. Feb 12 at 22:09