Here's my method:
Consider a rectangle that is $a \times b$. This is the interior of your structure where the thickness of the supporting members is neglected.

Then use trig to write the sides of the outlined triangle in terms of $a$ and $\theta$. In the small triangle at bottom-right, decompose it into two similar right triangles and write the relevant sides lengths in terms of $a$, $b$, $w$ and $\theta$.


Now you can represent the length of your beam as the sum of three lengths:

$$\begin{align} \text{Length} &= w\cdot \cot(\theta) + a\cdot \sec(\theta) + \frac{b-a\cdot \tan(\theta)}{\sin(\theta)} \\
&= w\cdot \cot(\theta) + a\cdot \sec(\theta) + b\cdot \csc(\theta) - a\cdot \sec(\theta)\\
&= w\cdot \cot(\theta) + b\cdot \csc(\theta)\end{align}$$
Now we have the total length of the beam in terms of just $b$, $w$ and $\theta$, so we need another equation in order to find $\theta$.
Notice that the pink and yellow triangles are similar, so write an equation involving the ratios of their corresponding sides:

$$\frac{b}{a\cdot\tan(\theta)}=\frac{a+w\cdot\csc(\theta)}{a}$$
I asked Wolfram|Alpha to solve this for $\theta$ and it gave:
$$\theta = 2 \tan^{-1}\left(\frac{\sqrt{a^2+b^2-w^2}-a}{b+w}\right)$$
Now we can find the angle from $a$, $b$ and $w$, and we can use the angle to find the length of the beam.
I checked this with your numbers: $a=38$, $b=31.75$ and $w=3.5$
This gave $\theta \approx 35.8265^{\circ}$ (which slightly concerns me, since your program rounded this down to 35.82) and $\text{Length} \approx 59.09 \text{in}$.
Last check: I found a long scrap of plywood in my garage that is 7.75 inches wide. I took it into my kitchen and laid it so it spanned a $2\times 3$ rectangle of floor tile. The formula gave 78.43 inches and it measured just over 78.5. Given the spacing of the grout between the tiles, I'm satisfied with this result.