# [PD] tri function in [expr~]

Claude Heiland-Allen claude at mathr.co.uk
Sun Aug 13 19:05:08 CEST 2017

```Hi Derek,

On 2017-08-13 17:33, Derek Holzer via Pd-list wrote:
> Dear list,
>
> I am transcribing some code from C to Pd expressions, and I am
> wondering how I might best get the tri function working since it's not
> native to expr.

My favourite triangle function is more expensive (division, branching)
but has a variable shape:

[expr~ if (\$v1 < \$v2, \$v1 / \$v2, (1 - \$v1) / (1 - \$v2))]

all of \$v1, \$v2, output are in [0..1), with \$v2=0.5 for symmetrical
triangle

> I have been using this expression as my triangle function:
>
> (min(\$v1, 1- \$v1) - 0.25) * 4
>
> So for this example:
>
> wave_x = .5-triangle((phasor-9/16)/(2/16))*.5;

here you have 0.5 - (... * 0.5)

> I have tried the following, which doesn't function correctly compared
> with the original C:
>
> [phasor~ 200]
> |
> [expr~ (\$v1-9./16.)/(2./16.)]
> |
> [expr~ (0.5 - (min(\$v1, 1.- \$v1) - 0.25) * 4.) * 0.5]

here you have (0.5 - ...) * 0.5, which isn't the same

> |
> [s~ wave_x]
>
> I am quite sure I have made some errors in the syntax somewhere, and I
> did trial-and-error many other combinations before arriving at this
> one. Would someone more math-literate than me care to help work this
> out?
>
> SIDENOTE: when is it necessary to force expr~ to consider a number as
> a float by using a decimal?
>
> (9/16) doesn't work but (9./16.) does.

I think int/int -> int with truncation is the most common occasion where
it matters in practice (except possibly overflow/wrapping with large
ints?).  If at least one argument is a float it should promote the other
to float too and give a float result.

> ((min(\$v1, 1- \$v1) - 0.25) * 4) works regardless of whether the 1 and
> the 4 have a decimal point following them or not.

\$v1 is a float so the 1 in 1-\$v1 is promoted from int to float.
min(float, float) is a float so the 4 is promoted to float too.

> Thanks much!
> Derek

hth,

Claude
--
https://mathr.co.uk

```