# Implementing sech

**URL:** <https://discuss.pytorch.org/t/implementing-sech/66862>\
**Category:** autograd\
**Created:** [January 16, 2020, 2:27pm UTC](https://discuss.pytorch.org/t/implementing-sech/66862 "2020-01-16T14:27:30Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![G.M](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/g.m/32/19266_2.png) [@G.M](https://discuss.pytorch.org/u/G.M)\
**Post date:** [January 16, 2020, 2:27pm UTC](https://discuss.pytorch.org/t/implementing-sech/66862/1 "2020-01-16T14:27:30Z")

</div>

I’m trying to implement _sech_ function, but Pytorch doesn’t have an internal implmentation for it as _tanh_ does. I came up with two solutions:

```auto
import torch as tc
import math

```

1. 

```auto
tanh_y = tc.tanh(input)
sech_y = tc.sqrt(1-a.pow(2))
#if it's in autograd.Function, I can then use the tanh_y and sech_y for backward.

```

1. 

```auto
a, b = tc.pow(math.e, input), tc.pow(math.e, -input)
#or:
#a = input.exp()
#b = a.reciprocal()
sech_y = 2/(a+b)
#tanh_y = (a-b)/(a+b)

```

I’m just curious about which one is better(perhaps faster), or does it not quite make any difference.  
Thanks for your time.

---

<div class="post-metadata">

**Author:** ![albanD](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/alband/32/215_2.png) [@albanD](https://discuss.pytorch.org/u/albanD)\
**Post date:** [January 16, 2020, 3:06pm UTC](https://discuss.pytorch.org/t/implementing-sech/66862/2 "2020-01-16T15:06:27Z")

</div>

Hi,

Given all the formulas I found online, `out = 1/torch.cosh(z)` should be the best (less total number of operations).

---

<div class="post-metadata">

**Author:** ![G.M](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/g.m/32/19266_2.png) [@G.M](https://discuss.pytorch.org/u/G.M)\
**Post date:** [January 17, 2020, 1:58am UTC](https://discuss.pytorch.org/t/implementing-sech/66862/3 "2020-01-17T01:58:14Z")

</div>

thx. I didn’t know there was a cosh function in Pytorch ☹
