{"id":8135,"date":"2023-09-11T05:00:29","date_gmt":"2023-09-10T23:30:29","guid":{"rendered":"https:\/\/tutorpython.com\/?p=8135"},"modified":"2023-10-19T15:14:01","modified_gmt":"2023-10-19T09:44:01","slug":"python-mathcopysign","status":"publish","type":"post","link":"https:\/\/tutorpython.com\/python-mathcopysign","title":{"rendered":"Python math.copysign"},"content":{"rendered":"<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_80 counter-hierarchy ez-toc-counter ez-toc-transparent ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\"><p class=\"ez-toc-title\" style=\"cursor:inherit\">In This Article<\/p>\n<\/div><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/tutorpython.com\/python-mathcopysign\/#Basics_of_Python_mathcopysign\" >Basics of Python math.copysign<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/tutorpython.com\/python-mathcopysign\/#Examples_of_using_mathcopysign\" >Examples of using math.copysign<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/tutorpython.com\/python-mathcopysign\/#Implementing_sgnx_signum_function\" >Implementing sgn(x) (signum function)<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/tutorpython.com\/python-mathcopysign\/#Simulating_a_Thermostat_using_mathcopysign\" >Simulating a Thermostat using math.copysign<\/a><\/li><\/ul><\/nav><\/div>\n<p>Python offers a wide array of mathematical functions with its <code>math<\/code> module. One of them, Python <code>math.copysign<\/code> function, allows us to copy the sign of one number to another number. In this article, we will begin by explaining the basics of Python <code>math.copysign<\/code>, and show some usage examples, before diving into two possible applications of the function. So, let us begin.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Basics_of_Python_mathcopysign\"><\/span>Basics of Python <code>math.copysign<\/code><span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>The function Python <code>math.copysign<\/code> takes two parameters <code>x<\/code> and <code>y<\/code>, then returns a new value having the absolute value of <code>x<\/code> and the sign of <code>y<\/code>. This function proves to be helpful if we ever need to make sure that one number has the sign of another.<\/p>\n<p>The simple code snippet below shows how to call Python <code>math.copysign<\/code>:<\/p>\n<pre class=\"language-python line-numbers\"><code>import math\r\n\r\nx = 3\r\ny = -5\r\n\r\nnew_number = math.copysign(x, y) # new_number will contain -3\r\n<\/code><\/pre>\n<p>In the above code, when the call to <code>math.copysign<\/code> returns, the value of <code>-3<\/code> will be returned and stored in the variable <code>new_number<\/code>.<\/p>\n<p>The variable <code>x<\/code> is the number whose magnitude will be used for the returned value of <code>math.copysign<\/code>.<\/p>\n<p>The variable <code>y<\/code> is the number whose sign will be used for the final returned value of the function. Let us dive into more examples of how to make use of the <code>math.copysign<\/code> function in Python.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Examples_of_using_mathcopysign\"><\/span>Examples of using <code>math.copysign<\/code><span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>The first example is shown in the code snippet below.<\/p>\n<p>In the example, we want to copy the sign of a positive number.<\/p>\n<pre class=\"language-python line-numbers\"><code>import math\r\n\r\nx = 2\r\ny = -2\r\nz = -7\r\n\r\nnum1 = math.copysign(x, z) # num1 will contain -2\r\nnum2 = math.copysign(y, z) # num2 will contain -2<\/code><\/pre>\n<p>In our code, we want to copy the sign of <code>z<\/code> (which is negative, since <code>z<\/code> stores the value <code>-7<\/code>).<\/p>\n<p>First, we combine the negative sign from <code>z<\/code> with the magnitude (or absolute value) of x. <code>math.copysign<\/code> will return <code>-2<\/code> . In the second call to <code>math.copysign<\/code>, we want to combine the magnitude of <code>y<\/code> with the negative sign from <code>z<\/code>. Since <code>y<\/code> already stores a negative value, and <code>z<\/code> is also negative, the function simply returns the value of <code>y<\/code> unchanged.<\/p>\n<p>The second example is similar, but we want to copy a positive sign to the magnitude of another number.<\/p>\n<pre class=\"language-python line-numbers\"><code>import math\r\n\r\nx = 5\r\ny = -5\r\nz = 10\r\n\r\nnum1 = math.copysign(x, z) # num1 will contain 5\r\nnum2 = math.copysign(y, z) # num2 will contain 5<\/code><\/pre>\n<p>Both calls to <code>math.copysign<\/code> return <code>5<\/code> since we are copying the sign of a positive number <code>10<\/code> (stored in the variable <code>z<\/code>). The first call is actually redundant since the signs of <code>x<\/code> and <code>z<\/code> are already the same.<\/p>\n<p>In summary, the behavior of <code>math.copysign<\/code> is as follows:<\/p>\n<span class=\"katex-eq\" data-katex-display=\"false\">math.copysign(x,y) = abs(x)\\times sgn(y) <\/span>\n<p>where <span class=\"katex-eq\" data-katex-display=\"false\">sgn(y)<\/span> is the sign\/signum function which returns the sign of <span class=\"katex-eq\" data-katex-display=\"false\">y<\/span>.<\/p>\n<p>In the next section, we will explore how to use <code>math.copysign<\/code> to define the signum function, since Python does not define any in its built-in libraries.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Implementing_sgnx_signum_function\"><\/span>Implementing <span class=\"katex-eq\" data-katex-display=\"false\">sgn(x)<\/span> (signum function)<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>The signum function is a mathematical function that is defined as follows:<\/p>\n<span class=\"katex-eq\" data-katex-display=\"false\">sgn(x) = \\begin{cases} 1 &amp; x&gt;0 \\\\ 0 &amp; x=0 \\\\ -1 &amp; x&lt;0\\end{cases} <\/span>\n<p>The numerical values returned are used to represent the sign of the input <span class=\"katex-eq\" data-katex-display=\"false\">x<\/span>. We can define our own version of the signum function by making use of <code>math.copysign<\/code>. The definition is as follows:<\/p>\n<span class=\"katex-eq\" data-katex-display=\"false\">sgn(x) = \\begin{cases} 0 &amp; x=0 \\\\ copysign(1, x) &amp; otherwise\\end{cases} <\/span>\n<p>Our signum function makes use of <code>math.copysign<\/code> when the value of <span class=\"katex-eq\" data-katex-display=\"false\">x<\/span> is not equal to <span class=\"katex-eq\" data-katex-display=\"false\">0<\/span>. The <code>copysign<\/code> function returns <code>+1<\/code> if <code>x &gt; 0<\/code> or <code>-1<\/code> if <code>x &lt; 0<\/code>.<\/p>\n<p>The code example below shows a Python definition for our very own signum function.<\/p>\n<pre class=\"language-python line-numbers\"><code>import math\r\n\r\ndef sgn(x):\r\n    if x==0:\r\n        return 0\r\n\r\n    return int(math.copysign(1, x))\r\n\r\nx = -12\r\ny = 0\r\nz = 23\r\n\r\nprint(f\"The sign of {x} is {sgn(x)}\")\r\nprint(f\"The sign of {y} is {sgn(y)}\")\r\nprint(f\"The sign of {z} is {sgn(z)}\")<\/code><\/pre>\n<p>Our code snippet also contains three different calls to our <code>sgn<\/code> function, checking for the signs of `x`, `y`, and <code>z<\/code>. The first one check . The output is as follows:<\/p>\n<p><img decoding=\"async\" class=\"aligncenter wp-image-8705 size-full\" src=\"https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_sgn-function-example-e1693931270342.png\" alt=\"output for user defined signum function using math.copysign in python\" width=\"806\" height=\"54\" srcset=\"https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_sgn-function-example-e1693931270342.png 806w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_sgn-function-example-e1693931270342-300x20.png 300w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_sgn-function-example-e1693931270342-768x51.png 768w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_sgn-function-example-e1693931270342-600x40.png 600w\" sizes=\"(max-width: 806px) 100vw, 806px\" \/><\/p>\n<p>As expected, <code>-12<\/code> has a negative sign, while <code>23<\/code> has a positive sign (represented by the <code>int<\/code> values <code>-1<\/code> and <code>1<\/code> respectively). The special case <code>0<\/code> is neutral, and has a sign represented by <code>0<\/code>.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Simulating_a_Thermostat_using_mathcopysign\"><\/span>Simulating a Thermostat using <code>math.copysign<\/code><span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>We want to explore how to make use of <code>math.copysign<\/code> to simulate a Thermostat.<\/p>\n<p>Specifically, we will make use of <code>math.copysign<\/code> to regulate the temperature.<\/p>\n<p>A Thermostat is a temperature-regulating device used to control the temperature of a space.<\/p>\n<p>The way a simple thermostat system works is that when the temperature rises above a setpoint (or target temperature), the thermostat switches off the heat source, but switches it back on when the temperature falls back below the setpoint.<\/p>\n<p>In this way, the thermostat maintains the temperature of the system around the target temperature.<\/p>\n<p>The code below demonstrates our Temperature regulation simulation.<\/p>\n<p>We have defined two classes: <code>HeatSource<\/code> to represent a heating source that can be powered ON or OFF, and the <code>Thermostat<\/code> class to monitor the current temperature of the <code>HeatSource<\/code>so that the temperature falls within a particular range.<\/p>\n<p>The source code is shown below:<\/p>\n<p>&nbsp;<\/p>\n<pre class=\"language-python line-numbers\"><code>from math import copysign\r\nimport random\r\nimport time\r\n\r\nclass HeatSource:\r\n    def __init__(self):\r\n        self.__isPoweredON = False\r\n        self.__currentTemp = 80.5\r\n        \r\n    @property\r\n    def currentTemp(self):\r\n        return self.__currentTemp   \r\n\r\n    @property\r\n    def isPoweredON(self):\r\n        return self.__isPoweredON       \r\n        \r\n    def powerON(self):\r\n        self.__isPoweredON = True\r\n        \r\n    def powerOFF(self):\r\n        self.__isPoweredON = False\r\n        \r\n    def updateTemp(self):\r\n        step = random.choice([0.50, 0.75])\r\n        if self.__isPoweredON:\r\n            self.__currentTemp += step\r\n            print(f\"Temperature heating up to {self.__currentTemp:.2f} Celsius\")\r\n            \r\n        else:\r\n            self.__currentTemp -= step\r\n            print(f\"Temperature cooling down to {self.__currentTemp:.2f} Celsius\")\r\n\r\nclass Thermostat:\r\n    def __init__(self, hs):\r\n        self.__heat_source = hs\r\n        self.__low_threshold = 83.5\r\n        self.__high_threshold = 85.5\r\n    \r\n    def checkTemp(self):\r\n        low_temp_diff = self.__heat_source.currentTemp - self.__low_threshold\r\n        high_temp_diff = self.__heat_source.currentTemp - self.__high_threshold\r\n        if int(copysign(1, low_temp_diff))==-1 and not self.__heat_source.isPoweredON:\r\n            self.__heat_source.powerON()\r\n            print(\"Power source switched ON\")\r\n            \r\n        elif int(copysign(1, high_temp_diff))==1 and self.__heat_source.isPoweredON:\r\n            self.__heat_source.powerOFF()\r\n            print(\"Power source switched OFF\")\r\n            \r\n        self.__heat_source.updateTemp()\r\n\r\n\r\ndef main():\r\n    hs = HeatSource()\r\n    th = Thermostat(hs)\r\n\r\n    print(f\"Start simulation with initial temperature {hs.currentTemp:.2f} Celsius\")\r\n\r\n    while True:\r\n        try:\r\n            th.checkTemp()\r\n            time.sleep(1.0)\r\n        \r\n        except KeyboardInterrupt:\r\n            print(\"End of simulation\")\r\n            break\r\n\r\nif __name__==\"__main__\":\r\n    main()<\/code><\/pre>\n<p>We see how <code>math.copysign<\/code> was used within the <code>checkTemp<\/code> method of <code>Thermostat<\/code>to determine when to turn the heat source ON or OFF. <code>checkTemp<\/code>does the regulation as follows:<\/p>\n<ul>\n<li><strong>Check for Low Temperature Threshold<\/strong>: <code>checkTemp<\/code> checks if the temperature is below the lower temperature threshold by checking the sign of the difference between the current temperature of the heat source and the low threshold. If the difference is negative, it switches on the heat source.<\/li>\n<li><strong>Check for High Temperature Threshold<\/strong>: In order to switch off the heat source, <code>checkTemp<\/code> calculates the difference between the current temperature of the heat source and the high threshold. If the difference is positive, it switches on the heat source so that the system heats up.<\/li>\n<\/ul>\n<p>When our script is run, we get something similar to the following:<\/p>\n<p><img fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter wp-image-8715 size-full\" src=\"https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_thermostat_simulation_copysign.png\" alt=\"output of thermostat simulation with math.copysign in python\" width=\"1292\" height=\"767\" srcset=\"https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_thermostat_simulation_copysign.png 1292w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_thermostat_simulation_copysign-300x178.png 300w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_thermostat_simulation_copysign-1024x608.png 1024w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_thermostat_simulation_copysign-768x456.png 768w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_thermostat_simulation_copysign-600x356.png 600w\" sizes=\"(max-width: 1292px) 100vw, 1292px\" \/><\/p>\n<p>Our heat source first starts with a temperature of <span class=\"katex-eq\" data-katex-display=\"false\">80.50\\degree C<\/span>.<\/p>\n<p>The thermostat allows the heat source to heat up to the high-temperature threshold of <span class=\"katex-eq\" data-katex-display=\"false\">85.50\\degree C<\/span>, before switching off the heat source to let it cool down.<\/p>\n<p>When the heat source cools below the low threshold of <span class=\"katex-eq\" data-katex-display=\"false\">83.50\\degree C<\/span>, our thermostat switches on the heat source again, and the process repeats. We added the ability to stop our simulation by pressing the key combination CTRL+C.<\/p>\n<p>In conclusion, we have seen how helpful <code>math.copysign<\/code> can be in allowing us to make decisions based on the sign of numbers.<\/p>\n<p>We have also shown how to use it to create our own implementation of the signum function in Python.<\/p>\n<p>We have also used the <code>math.copysign<\/code> function to implement a temperature regulation system.<\/p>\n<p>If you liked this tutorial, please feel free to check out our other tutorials on different topics relating to Python programming.<\/p>\n<p>Thanks, and Happy coding!!!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Python offers a wide array of mathematical functions with its math module&#8230;.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[28],"tags":[],"class_list":["post-8135","post","type-post","status-publish","format-standard","hentry","category-tutorial"],"acf":[],"_links":{"self":[{"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/posts\/8135","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/comments?post=8135"}],"version-history":[{"count":19,"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/posts\/8135\/revisions"}],"predecessor-version":[{"id":8723,"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/posts\/8135\/revisions\/8723"}],"wp:attachment":[{"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/media?parent=8135"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/categories?post=8135"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/tags?post=8135"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}