Message Boards Message Boards

Using a rule as an input to a function?

Posted 8 months ago

Hi, I'm trying to solve a self-consistent equation using Mathematica. I'm really new here. Essentially, I have a function f[T_] which outputs a different expression from every T_. I then I want to use the value f[T_] as the input for a second function, S[T_], but since the output of f[T_] is of the form {x->x0}, I can't just plug it into S[T_]. See code below, thank you!! (I also added a screenshot at the bottom)

    s[a_] := (
     Sqrt[a] E^(a/2) Sqrt[3/(
      2 \[Pi])] (E^a/
        a - ((1 + a) E^(-a/2) Sqrt[\[Pi]/6] Erfi[Sqrt[3/2] Sqrt[a]])/a^(
        3/2)))/Erfi[Sqrt[3/2] Sqrt[a]]
    f[T_] := FindRoot[s[x] - T*x, {x, 20}]
    f[T_] := Inactivate[FindRoot[s[x] - T*x, {x, 20}]]
    f[0.2] // Activate

Which outputs

{x -> 3.07401}

Then, if I try to define:

   S[T_] := s[f[T] // Activate]
   S[0.2]
    {(0.690988 2.71828^(0.5 (x -> 3.07401)) Sqrt[
      x -> 3.07401] (2.71828^(x -> 3.07401)/(x -> 3.07401) - (
        0.723601 2.71828^(-0.5 (x -> 3.07401))
          Erfi[1.22474 Sqrt[x -> 3.07401]] (1. + (x -> 3.07401)))/(x -> 
          3.07401)^(3/2)))/Erfi[1.22474 Sqrt[x -> 3.07401]]

Note the {x->3.07401} everywhere... Any idea how to solve this? I've been searching online for about an hour now.

enter image description here

POSTED BY: Nir Livne
3 Replies
Posted 8 months ago

That's a lifesaver for me, thank you!! I'm not really sure why, but without the [[1, -1]] in the definition of f:

f[T_] := FindRoot[s[x] - T*x, {x, 5}][[1, -1]]

I was having trouble using the FindRoot function without the Inactivate function

Problem solved, thank you! .enter image description here

POSTED BY: Nir Livne
Posted 8 months ago

Given an expression like this, {x -> 3.07401}, we can extract the 3.07401 in a few ways.

Part[{x -> 3.07401}, 1, -1]
(* also written as {x -> 3.07401}[[1, -1]] *)
Part[Values[{x -> 3.07401}], 1]
(* also written as Values[{x -> 3.07401}][[1]] *)
Lookup[{x -> 3.07401}, x]
ReplaceAll[x, {x -> 3.07401}]
(* also written as x /. {x -> 3.07401} *)

Now we need to decide where to do this extraction. You can apply it to the argument of S or you can apply it to the output of f. So, instead of S[T_] := s[f[T]], do

S[T_] := s[f[T][[1, -1]]]

Or instead of f[T_] := FindRoot[s[x] - T*x, {x, 20}] do

f[T_] := FindRoot[s[x] - T*x, {x, 20}][[1, -1]]

Side note: get rid of all of the Activate and Inactive stuff

POSTED BY: Eric Rimbey
Posted 8 months ago

That's a lifesaver for me, thank you!! I'm not really sure why, but without the [[1, -1]] in the definition of f:

f[T_] := FindRoot[s[x] - T*x, {x, 5}][[1, -1]]

I was having trouble using the FindRoot function without the Inactivate function

Problem solved, thank you! .enter image description here

POSTED BY: Nir Livne
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract